Functions

Python 3 supports an annotation syntax for function declarations.

  1. from typing import Callable, Iterator, Union, Optional, List
  2.  
  3. # This is how you annotate a function definition
  4. def stringify(num: int) -> str:
  5. return str(num)
  6.  
  7. # And here's how you specify multiple arguments
  8. def plus(num1: int, num2: int) -> int:
  9. return num1 + num2
  10.  
  11. # Add default value for an argument after the type annotation
  12. def f(num1: int, my_float: float = 3.5) -> float:
  13. return num1 + my_float
  14.  
  15. # This is how you annotate a callable (function) value
  16. x: Callable[[int, float], float] = f
  17.  
  18. # A generator function that yields ints is secretly just a function that
  19. # returns an iterator of ints, so that's how we annotate it
  20. def g(n: int) -> Iterator[int]:
  21. i = 0
  22. while i < n:
  23. yield i
  24. i += 1
  25.  
  26. # You can of course split a function annotation over multiple lines
  27. def send_email(address: Union[str, List[str]],
  28. sender: str,
  29. cc: Optional[List[str]],
  30. bcc: Optional[List[str]],
  31. subject='',
  32. body: Optional[List[str]] = None
  33. ) -> bool:
  34. ...
  35.  
  36. # An argument can be declared positional-only by giving it a name
  37. # starting with two underscores:
  38. def quux(__x: int) -> None:
  39. pass
  40.  
  41. quux(3) # Fine
  42. quux(__x=3) # Error