For all this, there is the excellent typing
library
In your case you could to
from typing import List, Tuple
and then you can type hint a variable by doing, for example,
age: List[float] = [28.2, 78.9, 40.5]
names: Tuple[str, str, str] = ('Simon', 'Alice', 'Bob')
and so on. The library is extremely flexible. For a dictionary, for example, it lets you specify the type of keys and values separately as well. If you read the documentation it will show you how to type hint even very complex stuff. It's worth noting that as of Python 3.9, most of the functionalities of this library have been incorporated into the python syntax. So unless you need the typing
library for complex cases (e.g. you need to type hint a Callable
, i.e. a function, or you need to specify multiple possible types using Union
etc.) you can just type hint things in python, so the examples above would become:
age: list[float] = [28.2, 78.9, 40.5]
names: tuple[str, str, str] = ('Simon', 'Alice', 'Bob')
without you needing to import any library. You still need the typing
library for Python 3.8 and below.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…