Functions
- from typing import Callable, Iterator, Union, Optional, List
-
- # This is how you annotate a function definition
- def stringify(num):
- # type: (int) -> str
- """Your function docstring goes here after the type definition."""
- return str(num)
-
- # This function has no parameters and also returns nothing. Annotations
- # can also be placed on the same line as their function headers.
- def greet_world(): # type: () -> None
- print "Hello, world!"
-
- # And here's how you specify multiple arguments
- def plus(num1, num2):
- # type: (int, int) -> int
- return num1 + num2
-
- # Add type annotations for arguments with default values as though they
- # had no defaults
- def f(num1, my_float=3.5):
- # type: (int, float) -> float
- return num1 + my_float
-
- # An argument can be declared positional-only by giving it a name
- # starting with two underscores
- def quux(__x):
- # type: (int) -> None
- pass
-
- quux(3) # Fine
- quux(__x=3) # Error
-
- # This is how you annotate a callable (function) value
- x = f # type: Callable[[int, float], float]
-
- # A generator function that yields ints is secretly just a function that
- # returns an iterator of ints, so that's how we annotate it
- def g(n):
- # type: (int) -> Iterator[int]
- i = 0
- while i < n:
- yield i
- i += 1
-
- # There's an alternative syntax for functions with many arguments
- def send_email(address, # type: Union[str, List[str]]
- sender, # type: str
- cc, # type: Optional[List[str]]
- bcc, # type: Optional[List[str]]
- subject='',
- body=None # type: List[str]
- ):
- # type: (...) -> bool
- <code>