python hints code example

Example 1: python type hints

def no_type_hint(arg):
  print(arg) # arg can be anything
  
def with_type_hint(arg: str):
  print(arg) # arg must be a string or a subtype of string

Example 2: python typing list of strings

from typing import List

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

Example 3: specify return type python function

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

Example 4: 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 5: type declaration python

def greeting(name: str) -> str:
    return 'Hello ' + name

Tags:

Misc Example