Created
March 28, 2022 05:13
-
-
Save musleh0001/0baf5077269a73e059bb9725b752dc16 to your computer and use it in GitHub Desktop.
Python Typing - Type Hints & Annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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