More function signatures
Here are a few more examples of adding type hints to function signatures.
If a function does not explicitly return a value, give it a returntype of None
. Using a None
result in a statically typedcontext results in a type check error:
- def p() -> None:
- print('hello')
- a = p() # Error: "p" does not return a value
Make sure to remember to include None
: if you don’t, the functionwill be dynamically typed. For example:
- def f():
- 1 + 'x' # No static type error (dynamically typed)
- def g() -> None:
- 1 + 'x' # Type check error (statically typed)
Arguments with default values can be annotated like so:
- def greeting(name: str, excited: bool = False) -> str:
- message = 'Hello, {}'.format(name)
- if excited:
- message += '!!!'
- return message
args
and *
kwargs
arguments can be annotated like so:
- def stars(*args: int, **kwargs: float) -> None:
- # 'args' has type 'Tuple[int, ...]' (a tuple of ints)
- # 'kwargs' has type 'Dict[str, float]' (a dict of strs to floats)
- for arg in args:
- print(arg)
- for key, value in kwargs:
- print(key, value)