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:

  1. def p() -> None:
  2. print('hello')
  3.  
  4. 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:

  1. def f():
  2. 1 + 'x' # No static type error (dynamically typed)
  3.  
  4. def g() -> None:
  5. 1 + 'x' # Type check error (statically typed)

Arguments with default values can be annotated like so:

  1. def greeting(name: str, excited: bool = False) -> str:
  2. message = 'Hello, {}'.format(name)
  3. if excited:
  4. message += '!!!'
  5. return message

args and *kwargs arguments can be annotated like so:

  1. def stars(*args: int, **kwargs: float) -> None:
  2. # 'args' has type 'Tuple[int, ...]' (a tuple of ints)
  3. # 'kwargs' has type 'Dict[str, float]' (a dict of strs to floats)
  4. for arg in args:
  5. print(arg)
  6. for key, value in kwargs:
  7. print(key, value)