Functions

  1. from typing import Callable, Iterator, Union, Optional, List
  2.  
  3. # This is how you annotate a function definition
  4. def stringify(num):
  5. # type: (int) -> str
  6. """Your function docstring goes here after the type definition."""
  7. return str(num)
  8.  
  9. # This function has no parameters and also returns nothing. Annotations
  10. # can also be placed on the same line as their function headers.
  11. def greet_world(): # type: () -> None
  12. print "Hello, world!"
  13.  
  14. # And here's how you specify multiple arguments
  15. def plus(num1, num2):
  16. # type: (int, int) -> int
  17. return num1 + num2
  18.  
  19. # Add type annotations for arguments with default values as though they
  20. # had no defaults
  21. def f(num1, my_float=3.5):
  22. # type: (int, float) -> float
  23. return num1 + my_float
  24.  
  25. # An argument can be declared positional-only by giving it a name
  26. # starting with two underscores
  27. def quux(__x):
  28. # type: (int) -> None
  29. pass
  30.  
  31. quux(3) # Fine
  32. quux(__x=3) # Error
  33.  
  34. # This is how you annotate a callable (function) value
  35. x = f # type: Callable[[int, float], float]
  36.  
  37. # A generator function that yields ints is secretly just a function that
  38. # returns an iterator of ints, so that's how we annotate it
  39. def g(n):
  40. # type: (int) -> Iterator[int]
  41. i = 0
  42. while i < n:
  43. yield i
  44. i += 1
  45.  
  46. # There's an alternative syntax for functions with many arguments
  47. def send_email(address, # type: Union[str, List[str]]
  48. sender, # type: str
  49. cc, # type: Optional[List[str]]
  50. bcc, # type: Optional[List[str]]
  51. subject='',
  52. body=None # type: List[str]
  53. ):
  54. # type: (...) -> bool
  55. <code>