Type Hints in Python
Type Hint | Meaning | Example(s) |
---|---|---|
int |
Integer | x: int = 5 |
float |
Floating-point number | pi: float = 3.14 |
str |
String | name: str = "John" |
bool |
Boolean | is_active: bool = True |
list |
List | numbers: list[int] = [1, 2, 3] |
tuple |
Tuple | coordinates: tuple[int, int] = (10, 20) |
dict |
Dictionary (string keys, any values) | person: dict[str, any] = {"name": "John", "age": 30} |
dict |
Dictionary (tuple keys, any values) | person: dict[tuple, any] = {(10,12): "John", (11,12): 30} |
set |
Set | unique_numbers: set[int] = {1, 2, 3} |
any |
any type (dynamic typing) | value: any = 10 |
Union |
Union of multiple types | mixed: Union[int, str] = 10 |
Optional |
Optional type (None or specified type) | age: Optional[int] = None |
Callable |
Callable (function or method) | operation: Callable[[int, int], int] = lambda x, y: x + y |
Iterable |
Iterable (e.g., list, tuple, dictionary keys) | items: Iterable[int] = [1, 2, 3] |
Iterator |
Iterator (e.g., returned by iter() function) | iter_obj: Iterator[int] = iter([1, 2, 3]) |
Generator |
Generator (function returning iterator) | def squares(n: int) -> Generator[int, None, None]: ... |
Type |
Type (class or type object) | cls: Type[MyClass] = MyClass |
ClassVar |
Class variable (shared among instances) | count: ClassVar[int] = 0 |
AnyStr |
Any string type (str or bytes) | data: AnyStr = "abc" |
NoReturn |
Used for functions that never return a value | def my_func() -> NoReturn: ... |
Literal |
Literal value (specific constant value) | status: Literal["success", "failure"] = "success" |
Final |
Final variable (cannot be reassigned) | MAX_SIZE: Final[int] = 100 |
NewType |
Creates a new distinct type (e.g., for validation) | UserId = NewType("UserId", int) |
Published on 23 Apr 2024
all tags
100daysofcode activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career ci-cd cli cloud code coding config configuration cp crud cryptography css csv database db design devops django docker email erp feelsgood filter fugitive gif gist git gnome gnome pomodoro grep hebrew http ide isbn-fetcher iso javascript job search js kanban kindle koans learning linkedin linux logger manjaro map markdown microservices mobi mtp neovim nodejs nvchad packages panda pastbin patch portfolio post postgres pytest python rails reduce refactoring reflections rest routes rspec ruby salesforce script scripting security sed shell sql string_replacement study tdd terminal testing tmux ttd version_control vim vim sort walkthrough webdev workflow