Appearance
Python Cheatsheet 2
typing
Union
py
from typing import Union
def square(x: Union[int, float]) -> float:
return x * xTyped Dictionary
py
from typing import TypedDict
class Movie(TypedDict):
name: str
year: int
movie = Movie(name="Avatar", year=2019)Optional
py
from typing import Optional
def nice_message(name: Optional[str]) -> None:
if name is None:
print("Hey random person!")
else:
print(f"Hi there, {name}!"")- In the case "name" can be either String or None!
- It cannot be anything else
Any
py
from typing import Any
def print_value(x: Any):
print(x)
print_value("I pretend to be Batman in the shower sometimes")Lambda Function
py
square = lambda x: x * x
square(10)py
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))