Annotations
Quick tutorial for python annotations check list.
Common types
Basic
numbers.py
# Numbers
int_num: int = 68
float_num: float = 32.2
double_num: double = 320.233
# String
name: str = "Peter"
by: bytes = b"test"
is_ok: bool = FalseSpecial
lists.py
# List
num_list: list = []
num_list_specific: list[int] = [1,2,3] ## Python 3.9
# Special
mytuple: tuple = ("apple", "banana", "cherry")
mytuple_specific: tuple[int, str, str] = (1, "banana", "cherry") # Python 3.9+
mySet: set[int] = {6, 7} ## Python 3.9
myDict: dict[str, int] = { "age" : 30 }
whatever: Any = False:::tip
For Python 3.8 and earlier, you may use the typing collection
from typing import List, Set, Dict, Tuple:::
Functions
functions.py
def add(a: int, b: int) -> int:
return a + b
def addVoid(a: int, b: int) -> None:
print( a + b )
from typing import Iterator # Python < 3.10+ in case
def gen(n: int) -> Iterator[int]:
i = 0
while i < n:
yield i
i += 1Special type method
Literal types
The Literal is used to define your own output types like enum
literal.py
from typing import Literal
def isBigger(a: int, b: int) -> Literal["yes", "no"]:
return "yes" if a > b else "no"You may also create a dynamic Literal with get_args
literal.py
from typing import Literal, get_args
major_types = Literal["CS" , "Math" , "Phy"]
major_list = [m for m in get_args(major_types)] # ["CS" , "Math" , "Phy"]type types
The type is used to define your own type for later used.
typeUsage.py
# Define a type
type Point = tuple[float, float]
myPoint: Point = (1.1, 4.7)
def makePoint(a: float, b: float) -> Point:
return (a, b)TypedDict dict objects
The TypedDict can be used to define a scheme / interface
from typing import TypedDict
import random
class StudentData(TypedDict):
student_id: int
major: major_types
gender: Literal["Male", "Female"]
gpa: float
std: StudentData = {
"student_id": 0,
"major": "CS",
"gender": "Male", "Female",
"gpa": 3.1
}
std_ls: list[StudentData] = [
{
"student_id": i + 1,
"major": random.choice(major_list),
"gender": random.choice(["Male", "Female"]),
"gpa": random.uniform(0, 4)
} for i in range(10)
] Callable Function Callback
Callable allow to create a callback function params with def()
callable.py
from typing import Callable
def process_data(data: list[int], operation: Callable[[int], int]) -> list[int]:
return [operation(item) for item in data]
def double(x: int) -> int:
return x * 2
doubled_numbers = process_data(
[1, 2, 3, 4],
double
)Union types
The Union is used to define mixed type.
union.py
from typing import Union
# Python 3.10+
mix_list: list[str | bool] = ["omg", True, "ok"]
mix_list_union: list[Union[str | bool]] = ["gg", True, "ok"]Optional types
The Optional is used to define optional params in functions.
optional.py
from typing import Optional
def isBigger(a: Optional[str] = None) -> None:
print(a)
# Other usage beside Optional
def isBigger(a: str | None = None) -> None:
print(a)Last updated on