Built-in Types
x = 1 |
Integer with no type |
x: int = 1 |
Integer with explicit type |
x: float = 1.0 |
Float |
x: bool = True |
Boolean |
x: str = "test" |
String |
s: bytes = b"test" |
Bytes |
Explicit Collections (from typing import ...)
x: List[int] = [1] |
Explicitly typed list |
x: Set[int] = { 2, 3 } |
Explicitly typed set |
x: Dict[str, float] = { "str": 1.0 } |
Explicitly typed dict |
x: Tuple = (1, "yes", 2.5) |
Explicitly typed tuple |
x: Tuple = (1, 2, 3) |
Explicitly typed open tuple |
x: list[int | str] = [1, 2, "test", "true"] |
Union type (version 3.10+) |
x: Optional[str] = x | None or Union[X, None] |
Optional type (union) |
⬆️ "test" if condition() else None |
Optional type (conditional) |
|
|
Collections (from typing import ...)
x: list[int] = [1] |
Array |
x: set[int] = { 1, 2 } |
Set |
x: dict[str, float] = { "test", 1.0 } |
Dictionary / Hash Table |
x: tuple[int, str, float] { 1, "yes", 2.5 } |
Tuple with 3 values |
x: tuple[int, ...] = { 1, 2, 3 } |
Tuple of variable size |
Functions (from typing import...)
def function(x: int) -> str |
Basic function with a return value |
def function(x: int = 1) -> str |
Basic function with a default value |
def function(x) |
Basic function with no argument type |
x: Callable[[int, float], float] |
Function as a class |
def gen(n: int) -> Iterator[int] |
Generator function that yields ints |
def function(self, *args: str, **kwargs: str) -> int |
All position args and keywords are strings |
|