# For collections on Python 3.9+, the type of the collection item is in brackets x: list[int] = [1] x: set[int] = {6, 7}
# For mappings, we need the types of both keys and values x: dict[str, float] = {"field": 2.0} # Python 3.9+
# For tuples of fixed size, we specify the types of all the elements x: tuple[int, str, float] = (3, "yes", 7.5) # Python 3.9+
# For tuples of variable size, we use one type and ellipsis x: tuple[int, ...] = (1, 2, 3) # Python 3.9+
# On Python 3.8 and earlier, the name of the collection type is # capitalized, and the type is imported from the 'typing' module from typing importList, Set, Dict, Tuple x: List[int] = [1] x: Set[int] = {6, 7} x: Dict[str, float] = {"field": 2.0} x: Tuple[int, str, float] = (3, "yes", 7.5) x: Tuple[int, ...] = (1, 2, 3)
from typing importUnion, Optional
# On Python 3.10+, use the | operator when something could be one of a few types x: list[int | str] = [3, 5, "test", "fun"] # Python 3.10+ # On earlier versions, use Union x: list[Union[int, str]] = [3, 5, "test", "fun"]
# Use Optional[X] for a value that could be None # Optional[X] is the same as X | None or Union[X, None] x: Optional[str] = "something"if some_condition() elseNone if x isnotNone: # Mypy 可以理解 if 语句,x在这里不会是None。 print(x.upper()) # 如果你知道一个值永远不会是None,但是 mypy 不理解的逻辑,可以使用assert。 assert x isnotNone print(x.upper())
classBankAccount: # The "__init__" method doesn't return anything, so it gets return # type "None" just like any other method that doesn't return anything def__init__(self, account_name: str, initial_balance: int = 0) -> None: # mypy will infer the correct types for these instance variables # based on the types of the parameters. self.account_name = account_name self.balance = initial_balance
# For instance methods, omit type for "self" defdeposit(self, amount: int) -> None: self.balance += amount
# User-defined classes are valid as types in annotations account: BankAccount = BankAccount("Alice", 400) deftransfer(src: BankAccount, dst: BankAccount, amount: int) -> None: src.withdraw(amount) dst.deposit(amount)
# Functions that accept BankAccount also accept any subclass of BankAccount! classAuditedBankAccount(BankAccount): # You can optionally declare instance variables in the class body audit_log: list[str]
audited = AuditedBankAccount("Bob", 300) transfer(audited, account, 100) # type checks!
# You can use the ClassVar annotation to declare a class variable classCar: seats: ClassVar[int] = 4 passengers: ClassVar[list[str]]
# If you want dynamic attributes on your class, have it # override "__setattr__" or "__getattr__" classA: # This will allow assignment to any A.x, if x is the same type as "value" # (use "value: Any" to allow arbitrary types) def__setattr__(self, name: str, value: int) -> None: ...
# This will allow access to any A.x, if x is compatible with the return type def__getattr__(self, name: str) -> int: ...
a.foo = 42# Works a.bar = 'Ex-parrot'# Fails type checking
poetry new <project-name> # Create a new project poetry init # Create pyproject.toml
包管理
1 2 3 4 5 6 7 8
poetry add <package_name> # Add a new lib poetry remove <package_name> # Remove a lib poetry update <package_name> # Update a lib poetry show <package_name> # show a lib poetry build # Create a package poetry version prerelease # Update the alpha version of the next release number. poetry version patch # Update the patch version of the next release number. poetry install # install dependencies