Typed Dictionary
Used to define dictionaries with a fixed set of keys and their value types
from typing import TypedDict
class User(TypedDict):
id: int
name: str
is_active: bool
u: User = {"id": 1, "name": "Vignesh", "is_active": True}
Union
Used when something can be more than one type
from typing import Union
def square(x: Union[int, float]) -> Union[int, float]:
return x * x
Optional
The value can be either a specific type or None
from typing import Optional
def get_name(user_id: int) -> Optional[str]:
if user_id == 1:
return "Vignesh"
return None
Any
Type can be anything, same as Typescript any
from typing import Any
def print_value(x: Any) -> None:
print(x)
Lambda Function
small function written in one line
add = lambda a, b: a + b
print(add(5, 3)) # 8