WebFeb 16, 2024 · 1 Answer Sorted by: 12 I would use the typing module from typing import List def foo (bar: List [str]): pass The reason is typing contains so many type hints and the ability to create your own, specify callables, etc. Definitely check it out. Edit: I guess as of Python 3.9 typing is deprecated (RIP). WebJan 19, 2024 · It was implemented in Python 3.8 (Same as typing.Literal) The docstring is thoroughly instructive: def get_origin (tp): """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types.
python - Determining if object is of typing.Literal type - Stack Overflow
WebDeclaring literal variables # You must explicitly add an annotation to a variable to declare that it has a literal type: a: Literal[19] = 19 reveal_type(a) # Revealed type is "Literal [19]" … WebJan 15, 2024 · You can type hint it as Union [None, Type [list], Type [dict], Literal ["list", "dict"]] (import Union and Type from typing) Just watch out, as this would also accept a subclass of list or dict Share Improve this answer Follow answered Jan 15, 2024 at 20:29 Goshal 16 1 Thanks! That's what I was looking for. flight from melbourne to san francisco
Type Hints in Python — Everything You Need To Know In 5 Minutes
WebIs there a way to give the same type hint in the dictionary literal declaration? The following does not achieve what I am looking for: Add a Union [...] type hint at the end of the literal declaration? 'area': calc_area (corners), 'pins': None } # type: Union [Line, Tuple [float, float], float, List [Pin]] Adding a type-hint to every line: WebSep 19, 2024 · Type hinting is a great way to be explicit about the data types that you expect in your code. But sometimes, you want to use type hints without fully restricting how your users can use the objects. For example, perhaps you want to specify a tuple that should contain only integers, but the number of integers can be arbitrary. WebYou can't specify that your function returns only a subset of a type's values using type hinting alone. As the name implies, type hinting is all about types not values. However, you can create a new enum.Enum subtype that only has the values you're going to return and use it in the function. chemistry hive