Learned about this today, so I'm organizing it!
Reference: python docs
-
The Python runtime does not enforce type annotations on functions or variables
- You need to use an IDE or type checker to verify them
-
You can provide type hints to indicate types when using methods
- Function annotations can be used for Parameters and return values, but they are not mandatory!
- Function annotations can be used to provide type checking
- However, Lambda does not support annotations!
ex1) parameter
def foo(a: expression, b: expression = 2):
...ex2) excess parameter ( *args, **kwargs )
def foo(*args: expression, **kwargs: expression):
...ex)
def sum() -> expression:
...+
: Additionally, you can also use aliases!
ex)
from typing import List
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])