type annotations python code example

Example 1: python typing list of strings

from typing import List

def my_func(l: List[int]):
    pass

Example 2: specify return type python function

def greeting(name: str) -> str:
  return 'Hello, {}'.format(name)

Example 3: typing generator python

# Iterator
def infinite_stream(start: int) -> Iterator[int]:
    while True:
        yield start
        start += 1

# Generator        
def infinite_stream(start: int) -> Generator[int, None, None]:
    while True:
        yield start
        start += 1

Example 4: python type annotations

# Some basic type annotations
#
# Note that type annotations are not enforced by the interpreter.
# The code
# 	a: int = 5
# 	a = "hello"
# is valid Python.

# A built-in library with some extra types that can be used 
# for annotations
from typing import Union, Optional, List, Tuple

a: int = 6 # A variable annotated as int

# This denotes a variable that will hold ints and floats over 
# the course of its usage.
two_types: Union[int, float] = 5.6
  
# This variable could hold str or it could be None. This is
# effectively the same as typing opt as Union[str, None].
opt: Optional[str] = None
  
# This is a function with type annotations; it takes two
# int parameters and returns bool.
def annotated_func(x: int, y: int) -> bool:
  return x > y

# You can also annotate a certain data structure and the type of
# data you intend it to contain.
l: List[int] = [1, 2, 3, 4]
t: Tuple[chr] = ('a', 'b', 'c', 'd')

# In Python 3.9+, list[<TYPE>] and tuple[<TYPE>] can be used
# instead. They're aliases for typing.List and typing.Tuple.

Example 5: python type hint list

# For collections, the name of the type is capitalized, and the
# name of the type inside the collection is in brackets
x: List[int] = [1]
x: Set[int] = {6, 7}
  
# For simple built-in types, just use the name of the type
x: int = 1
x: float = 1.0
x: bool = True
x: str = "test"
x: bytes = b"test"

Example 6: python optional type annotation

from custom_module import SomeClass
from typing import Optional

class SubClass:
    a_reference: Optional[SomeClass] # Provides info that a_reference may be 'None'.

    def __init__(self):
        self.a_reference = None