Skip to content

Instantly share code, notes, and snippets.

@musleh0001
Created March 28, 2022 05:13
Show Gist options
  • Save musleh0001/0baf5077269a73e059bb9725b752dc16 to your computer and use it in GitHub Desktop.
Save musleh0001/0baf5077269a73e059bb9725b752dc16 to your computer and use it in GitHub Desktop.
Python Typing - Type Hints & Annotations
# static code analysis (mypy)
# mypy main.py [check miss match]
from typing import List, Dict, Set, Optional, Any, Sequence, TypeVar
def add_numbers(a: int, b: int, c: int) -> None:
print(a + b + c)
add_numbers(1, 2, 3)
x: List[List[int]] = [[1, 2, 3], [1, 2, 3]] # nested list
x: Dict[str, str] = {"a", "b"}
x: Set[str] = {"a", "b"}
Vector = List[float]
def foo(v: Vector) -> Vector:
return v
foo()
# Optional
def foo(output: Optional[bool]=False):
pass
foo()
# Sequence: anything that can be indexed str, list, typle
def foo(seq: Sequence[str]):
pass
# generic
T = TypeVar('T')
def get_item(lst: List[T], index: int) -> T:
return lst[index]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment