Python Typing Type Hints and Annotations
URL:https://youtu.be/QORvB-_mbZ0Channel/Host:Tech With TimReference:TypingPublish Date:2021.09.29Reviewed Date:15
- 
- To do a type annotation for items in a list (a vector basically) you can pass the type like 
list[int]but this can also be used to pass things like a list of int lists:list[list[int]] - To use 
Listas a type you need tofrom typing import List:List[List[int]] 
 - To do a type annotation for items in a list (a vector basically) you can pass the type like 
 - 
from typing import Dict- Dictionary typing: 
x: Dict[str, str] = {"a": "b"} 
 - 
from typing import Set- Set typing: 
x: Set[str] = {"a", "b"} 
 - 
- 
Custom Typing:
 - 
from typing import List Vector = List[float] def foo(v: Vector) -> Vector: print(v) - 

 - 
Can also use our own custom types like this:
 - 
from typing import List Vector = List[float] Vectors = List[Vector] def foo(v: Vectors) -> Vectors: print(v) 
 - 
 - 
- 
Optional typing
 - 
from typing import Optional def foo(output: Optional[bool]=False): pass foo() 
 - 
 - 
- 
Any Type is the same as not adding an annotation but more explicit
 - 
from typing import Any def foo(output: Any): pass 
 - 
 - 
- 
Sequence Type
 - 
from typing import Sequence def foo(seq: Sequence[str]): pass foo("Hello") # This is fine because a string is a sequence of characters foo(("a", "b", "c")) # a Tuple is an ordered and immutable indexed Object foo(["a", "b", "c"]) # A list is an ordered and indexed object foo({1, 2, 3}) # A set is hashed and not indexed or ordered so it cannot be a sequence foo(1) #>>> Last one throws an error because static analysis determines that it is an incompabile type 
 - 
 - 
- 
Tuple Type:
 - 
from typing import Tuple # This is an error because the tuple can contain items of differing types # so you need to specify the type of each item within it x: Tuple[int] = (1, 2, 3) x: Tuple[int, int, int] = (1, 2, 3) 
 - 
 - 
- 
Callable Type:
 - 
from typing import callable, Optional def foo(func: Callable[[int, int, Optional[int]], int]) -> None: func(1, 2) def add(x: int, y: int) -> int: return x + y foo(add) #=================================================================# def foo() -> Callable[[int, int, Optional[int]], int]): def add(x: int, y: int) -> int: return x + y return add foo() #=================================================================# def foo() -> Callable[[int, int], int]): func: Callable[[int, int], int]) = Lambda x, y: x + y return func foo() 
 - 
 - 
- 
Generics:
 - 
from typing import TypeVar, List T = TypeVar('T') def get_item(lst: List[T], index: int) -> T: return lst[index] 
 - 
 
Backlinks