Kiểm tra kiểu hoạt động như thế nào trong Python?
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc Show
This module provides runtime support for type hints. The most fundamental support consists of the types , , , , and . For a full specification, please see PEP 484. For a simplified introduction to type hints, see PEP 483 The function below takes and returns a string and is annotated as follows def greeting(name: str) -> str: return 'Hello ' + name In the function Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])31, the argument Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])32 is expected to be of type and the return type . Subtypes are accepted as arguments New features are frequently added to the Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25 module. The typing_extensions package provides backports of these new features to older versions of Python For a summary of deprecated features and a deprecation timeline, please see See also The documentation at https. //typing. readthedocs. io/ serves as useful reference for type system features, useful typing related tools and typing best practices Relevant PEPsSince the initial introduction of type hints in PEP 484 and PEP 483, a number of PEPs have modified and enhanced Python’s framework for type annotations. Bao gồm các
Type aliasesA type alias is defined by assigning the type to the alias. In this example, Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])58 and Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])59 will be treated as interchangeable synonyms Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) Type aliases are useful for simplifying complex type signatures. For example from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ... Note that Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])60 as a type hint is a special case and is replaced by Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])61 NewTypeUse the helper to create distinct types from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313) The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1) You may still perform all Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])63 operations on a variable of type Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])64, but the result will always be of type Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])63. This lets you pass in a Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])64 wherever an Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])63 might be expected, but will prevent you from accidentally creating a Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])64 in an invalid way # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341) Note that these checks are enforced only by the static type checker. At runtime, the statement Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])69 will make Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])70 a callable that immediately returns whatever parameter you pass it. That means the expression Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])71 does not create a new class or introduce much overhead beyond that of a regular function call More precisely, the expression Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])72 is always true at runtime It is invalid to create a subtype of Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])70 from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass However, it is possible to create a based on a ‘derived’ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])62 from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId) and typechecking for Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])76 will work as expected Xem PEP 484 để biết thêm chi tiết Ghi chú Nhớ lại rằng việc sử dụng bí danh kiểu khai báo hai kiểu tương đương với nhau. Việc thực hiện Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])77 sẽ khiến trình kiểm tra kiểu tĩnh coi Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])78 chính xác tương đương với Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])79 trong mọi trường hợp. Điều này hữu ích khi bạn muốn đơn giản hóa chữ ký loại phức tạp Ngược lại, Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])62 tuyên bố một kiểu là kiểu con của kiểu khác. Thực hiện Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])81 sẽ khiến trình kiểm tra loại tĩnh coi Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])70 là một lớp con của Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])79, có nghĩa là giá trị của loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])79 không thể được sử dụng ở những nơi mong đợi giá trị của loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])70. Điều này hữu ích khi bạn muốn ngăn ngừa các lỗi logic với chi phí thời gian chạy tối thiểu Mới trong phiên bản 3. 5. 2 Đã thay đổi trong phiên bản 3. 10. ______1_______62 bây giờ là một lớp chứ không phải là một hàm. Có một số chi phí thời gian chạy bổ sung khi gọi Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])62 qua một chức năng thông thường. Tuy nhiên, chi phí này sẽ giảm trong 3. 11. 0. Có thể gọiCác khung mong đợi các chức năng gọi lại của các chữ ký cụ thể có thể được gợi ý loại bằng cách sử dụng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])88 Ví dụ from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update Có thể khai báo kiểu trả về của một hàm có thể gọi được mà không chỉ định chữ ký cuộc gọi bằng cách thay thế dấu chấm lửng bằng chữ cho danh sách các đối số trong gợi ý kiểu. Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])89 Các cuộc gọi lấy các cuộc gọi khác làm đối số có thể chỉ ra rằng các loại tham số của chúng phụ thuộc vào nhau bằng cách sử dụng. Ngoài ra, nếu khả năng gọi đó thêm hoặc xóa đối số khỏi các khả năng gọi khác, thì toán tử có thể được sử dụng. Chúng có dạng tương ứng là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])92 và Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])93 Đã thay đổi trong phiên bản 3. 10. ______1_______28 hiện hỗ trợ và. Xem PEP 612 để biết thêm chi tiết. See also Tài liệu về và cung cấp các ví dụ về cách sử dụng trong Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])28 thuốc gốcVì thông tin loại về các đối tượng được giữ trong vùng chứa không thể được suy luận tĩnh theo cách chung chung, nên các lớp cơ sở trừu tượng đã được mở rộng để hỗ trợ đăng ký biểu thị các loại dự kiến cho các phần tử vùng chứa from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ... Generics có thể được tham số hóa bằng cách sử dụng một nhà máy có sẵn trong cách gõ được gọi là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])0 Loại chung do người dùng xác địnhMột lớp do người dùng định nghĩa có thể được định nghĩa là một lớp chung Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])1 from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...01 như một lớp cơ sở định nghĩa rằng lớp from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...02 nhận một tham số loại duy nhất from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...03. Điều này cũng làm cho from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...03 hợp lệ như một kiểu trong thân lớp Lớp cơ sở định nghĩa sao cho from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...07 có giá trị như một loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])2 Một loại chung có thể có bất kỳ số lượng biến loại nào. Tất cả các loại được phép làm tham số cho một loại chung Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])3 Mỗi đối số biến loại phải khác biệt. Điều này là không hợp lệ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])4 Bạn có thể sử dụng nhiều kế thừa với Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])5 Khi kế thừa từ các lớp chung, một số biến kiểu có thể được sửa Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])6 Trong trường hợp này, from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...11 có một tham số duy nhất, from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...03 Sử dụng một lớp chung mà không chỉ định tham số loại giả định cho từng vị trí. Trong ví dụ sau, from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...14 không phải là chung chung nhưng hoàn toàn kế thừa từ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...15 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])7 Bí danh loại chung do người dùng xác định cũng được hỗ trợ. ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])8 Đã thay đổi trong phiên bản 3. 7. không còn siêu dữ liệu tùy chỉnh nữa. Generics do người dùng định nghĩa cho các biểu thức tham số cũng được hỗ trợ thông qua các biến đặc tả tham số ở dạng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...17. Hành vi phù hợp với các biến loại' được mô tả ở trên vì các biến đặc tả tham số được mô-đun đánh máy coi là một biến loại chuyên biệt. Một ngoại lệ cho điều này là một danh sách các loại có thể được sử dụng để thay thế một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])9 Hơn nữa, một biến chung chỉ có một biến đặc tả tham số sẽ chấp nhận danh sách tham số ở dạng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...19 và cả from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...20 vì lý do thẩm mỹ. Trong nội bộ, cái sau được chuyển đổi thành cái trước, vì vậy những điều sau đây là tương đương from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...0 Xin lưu ý rằng thuốc generic với có thể không đúng với from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...22 sau khi thay thế trong một số trường hợp vì chúng chủ yếu dành cho kiểm tra loại tĩnh Đã thay đổi trong phiên bản 3. 10. hiện có thể được tham số hóa qua các biểu thức tham số. Xem và PEP 612 để biết thêm chi tiết. Lớp chung do người dùng định nghĩa có thể có ABC làm lớp cơ sở mà không có xung đột siêu dữ liệu. Siêu dữ liệu chung không được hỗ trợ. Kết quả của việc tham số hóa các khái quát được lưu vào bộ đệm và hầu hết các loại trong mô-đun gõ đều có thể băm và có thể so sánh bằng nhau loạiMột loại đặc biệt của loại là. Trình kiểm tra loại tĩnh sẽ coi mọi loại là tương thích với và tương thích với mọi loại Điều này có nghĩa là có thể thực hiện bất kỳ thao tác hoặc lệnh gọi phương thức nào trên một giá trị kiểu và gán nó cho bất kỳ biến nào from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...1 Lưu ý rằng không có kiểm tra loại nào được thực hiện khi gán giá trị của loại cho loại chính xác hơn. Ví dụ: trình kiểm tra kiểu tĩnh không báo lỗi khi gán from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...31 cho from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...32 mặc dù from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...32 đã được khai báo là kiểu và nhận một giá trị trong thời gian chạy Hơn nữa, tất cả các hàm không có kiểu trả về hoặc kiểu tham số sẽ mặc định sử dụng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...2 Hành vi này cho phép được sử dụng như một lối thoát hiểm khi bạn cần kết hợp mã được nhập động và tĩnh Contrast the behavior of with the behavior of . Tương tự như , mỗi loại là một kiểu con của. Tuy nhiên, không giống như , điều ngược lại là không đúng. không phải là một kiểu con của mọi kiểu khác Điều đó có nghĩa là khi loại của một giá trị là , trình kiểm tra loại sẽ từ chối hầu hết mọi hoạt động trên nó và gán nó cho một biến (hoặc sử dụng nó làm giá trị trả về) của một loại chuyên biệt hơn là lỗi loại. Ví dụ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...3 Sử dụng để chỉ ra rằng một giá trị có thể là bất kỳ loại nào theo cách an toàn. Sử dụng để chỉ ra rằng một giá trị được nhập động Phân nhóm danh nghĩa và cấu trúcBan đầu, PEP 484 đã định nghĩa hệ thống kiểu tĩnh Python là sử dụng kiểu con danh nghĩa. Điều này có nghĩa là một lớp from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...47 được cho phép khi một lớp from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...48 được mong đợi nếu và chỉ khi from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...47 là một lớp con của from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...48 Yêu cầu này trước đây cũng được áp dụng cho các lớp cơ sở trừu tượng, chẳng hạn như. Vấn đề với cách tiếp cận này là một lớp phải được đánh dấu rõ ràng để hỗ trợ chúng, điều này không phổ biến và không giống như những gì người ta thường làm trong mã Python được gõ động thành ngữ. Ví dụ: điều này phù hợp với PEP 484 from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...4 PEP 544 cho phép giải quyết vấn đề này bằng cách cho phép người dùng viết đoạn mã trên mà không có các lớp cơ sở rõ ràng trong định nghĩa lớp, cho phép from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...52 được coi là một kiểu con của cả from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...53 và from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...54 bởi trình kiểm tra kiểu tĩnh. Điều này được gọi là phân nhóm cấu trúc (hoặc phân nhóm tĩnh) from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...5 Ngoài ra, bằng cách phân lớp một lớp đặc biệt, người dùng có thể xác định các giao thức tùy chỉnh mới để tận hưởng đầy đủ phân nhóm cấu trúc (xem ví dụ bên dưới) nội dung mô-đunMô-đun định nghĩa các lớp, chức năng và trình trang trí sau Ghi chú Mô-đun này xác định một số loại là các lớp con của các lớp thư viện tiêu chuẩn đã tồn tại từ trước, cũng mở rộng để hỗ trợ các biến loại bên trong from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57. Các loại này trở nên dư thừa trong Python 3. 9 khi các lớp có sẵn tương ứng được tăng cường để hỗ trợ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57 Các loại dự phòng không được dùng nữa kể từ Python 3. 9 nhưng trình thông dịch sẽ không đưa ra cảnh báo phản đối nào. Dự kiến, trình kiểm tra loại sẽ gắn cờ các loại không dùng nữa khi chương trình được kiểm tra nhắm mục tiêu Python 3. 9 hoặc mới hơn Các loại không dùng nữa sẽ bị xóa khỏi mô-đun trong phiên bản Python đầu tiên được phát hành 5 năm sau khi phát hành Python 3. 9. 0. Xem chi tiết trong PEP 585—Type Gợi ý Generics Trong Bộ sưu tập Tiêu chuẩn Kiểu gõ đặc biệtcác loại đặc biệtChúng có thể được sử dụng làm loại trong chú thích và không hỗ trợ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57đang gõ. Bất kỳ Loại đặc biệt cho biết loại không bị ràng buộc
Đã thay đổi trong phiên bản 3. 11. hiện có thể được sử dụng làm lớp cơ sở. Điều này có thể hữu ích để tránh các lỗi trình kiểm tra kiểu với các lớp có thể gõ ở bất cứ đâu hoặc rất năng động. đang gõ. Chuỗi ký tựLoại đặc biệt chỉ bao gồm các chuỗi ký tự. Một chuỗi ký tự tương thích với Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])56, cũng như một ký tự khác là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])56, nhưng một đối tượng được nhập như chỉ là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])33 thì không. Một chuỗi được tạo bằng cách kết hợp các đối tượng được nhập vào Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])56 cũng được chấp nhận là một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])56 Thí dụ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...6 Điều này hữu ích cho các API nhạy cảm nơi các chuỗi tùy ý do người dùng tạo có thể gây ra sự cố. Ví dụ: hai trường hợp trên tạo ra lỗi trình kiểm tra kiểu có thể dễ bị tấn công SQL injection Xem PEP 675 để biết thêm chi tiết Mới trong phiên bản 3. 11 đang gõ. Không bao giờLoại dưới cùng, một loại không có thành viên Điều này có thể được sử dụng để xác định một hàm không bao giờ được gọi hoặc một hàm không bao giờ trả về from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...7 Mới trong phiên bản 3. 11. Trên các phiên bản Python cũ hơn, có thể được sử dụng để diễn đạt cùng một khái niệm. from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...70 đã được thêm vào để làm cho ý nghĩa rõ ràng hơn. đang gõ. Không trả lại Loại đặc biệt chỉ ra rằng một hàm không bao giờ trả về. Ví dụ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...8 from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...69 cũng có thể được sử dụng làm loại dưới cùng, loại không có giá trị. Bắt đầu bằng Python 3. 11, loại nên được sử dụng cho khái niệm này để thay thế. Người kiểm tra loại nên đối xử với cả hai như nhau New in version 3. 5. 4 Mới trong phiên bản 3. 6. 2 đang gõ. Bản thânLoại đặc biệt để đại diện cho lớp kèm theo hiện tại. Ví dụ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...9 Chú thích này về mặt ngữ nghĩa tương đương với chú thích sau, mặc dù theo cách ngắn gọn hơn from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)0 Nói chung nếu một cái gì đó hiện đang theo mô hình của from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)1 You should use as calls to from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...74 would have from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...75 as the return type and not from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...76 Các trường hợp sử dụng phổ biến khác bao gồm
Xem PEP 673 để biết thêm chi tiết Mới trong phiên bản 3. 11 đang gõ. TypeAliasSpecial annotation for explicitly declaring a . Ví dụ from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)2 Xem PEP 613 để biết thêm chi tiết về bí danh loại rõ ràng New in version 3. 10 các hình thức đặc biệtChúng có thể được sử dụng làm loại trong chú thích bằng cách sử dụng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57, mỗi loại có một cú pháp duy nhấtđang gõ. Tuple Tuple type; from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...81 is the type of a tuple of two items with the first item of type X and the second of type Y. The type of the empty tuple can be written as from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...82 Example. from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...83 is a tuple of two elements corresponding to type variables T1 and T2. from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...84 is a tuple of an int, a float and a string To specify a variable-length tuple of homogeneous type, use literal ellipsis, e. g. from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...85. A plain is equivalent to from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...87, and in turn to Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . typing. Union Union type; from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...91 is equivalent to Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])45 and means either X or Y To define a union, use e. g. from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...93 or the shorthand from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...94. Using that shorthand is recommended. Details
Changed in version 3. 7. Don’t remove explicit subclasses from unions at runtime. Changed in version 3. 10. Unions can now be written as Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])45. See . typing. Optional Optional type from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...98 is equivalent to from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...99 (or from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)00) Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)01 qualifier on its type annotation just because it is optional. For example from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)7 On the other hand, if an explicit value of Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])60 is allowed, the use of from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)01 is appropriate, whether the argument is optional or not. For example from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)8 Changed in version 3. 10. Optional can now be written as from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...99. See . typing. Có thể gọi Loại có thể gọi được; Cú pháp đăng ký phải luôn được sử dụng với chính xác hai giá trị. danh sách đối số và kiểu trả về. Danh sách đối số phải là một danh sách các loại hoặc dấu chấm lửng; Không có cú pháp để chỉ ra các đối số tùy chọn hoặc từ khóa; . Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])89 (dấu chấm lửng theo nghĩa đen) có thể được sử dụng để nhập gợi ý có thể gọi được, lấy bất kỳ số lượng đối số nào và trả về from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)07. Một đồng bằng tương đương với from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)09, và đến lượt nó Các cuộc gọi lấy các cuộc gọi khác làm đối số có thể chỉ ra rằng các loại tham số của chúng phụ thuộc vào nhau bằng cách sử dụng. Ngoài ra, nếu khả năng gọi đó thêm hoặc xóa đối số khỏi các khả năng gọi khác, thì toán tử có thể được sử dụng. Chúng có dạng tương ứng là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])92 và Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])93 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . Đã thay đổi trong phiên bản 3. 10. ______1_______28 hiện hỗ trợ và. Xem PEP 612 để biết thêm chi tiết. See also Tài liệu về và cung cấp các ví dụ về cách sử dụng với Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])28đang gõ. Nối Được sử dụng với và để nhập chú thích một thứ có thể gọi được cao hơn để thêm, xóa hoặc chuyển đổi các tham số của một thứ có thể gọi khác. Cách sử dụng ở dạng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)25. Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])49 hiện chỉ hợp lệ khi được sử dụng làm đối số đầu tiên cho một. Tham số cuối cùng của Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])49 phải là dấu chấm lửng hoặc ( from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)30) Ví dụ: để chú thích một trình trang trí from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)31 cung cấp a cho hàm được trang trí, có thể sử dụng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])49 để chỉ ra rằng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)31 mong đợi một hàm có thể gọi được, trong đó nhận vào một đối số đầu tiên là ____12_______35 và trả về một hàm có thể gọi được với một chữ ký kiểu khác. Trong trường hợp này, chỉ ra rằng các loại tham số của hàm có thể gọi được trả về phụ thuộc vào các loại tham số của hàm có thể gọi được truyền vào from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)9 New in version 3. 10 See also
Một biến được chú thích bằng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)41 có thể chấp nhận giá trị loại from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)41. Ngược lại, một biến được chú thích bằng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)43 có thể chấp nhận các giá trị là chính các lớp – cụ thể, nó sẽ chấp nhận đối tượng lớp của from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)41. Ví dụ def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)0 Lưu ý rằng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)43 là hiệp phương sai def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)1 Thực tế là from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)43 là hiệp phương sai ngụ ý rằng tất cả các lớp con của from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)41 nên triển khai cùng chữ ký hàm tạo và chữ ký phương thức lớp như from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)41. Trình kiểm tra loại sẽ gắn cờ vi phạm điều này, nhưng cũng nên cho phép các lệnh gọi hàm tạo trong các lớp con khớp với các lệnh gọi hàm tạo trong lớp cơ sở được chỉ định. Cách trình kiểm tra loại được yêu cầu để xử lý trường hợp cụ thể này có thể thay đổi trong các phiên bản PEP 484 trong tương lai Các tham số pháp lý duy nhất cho là các lớp, , và liên kết của bất kỳ loại nào trong số này. Ví dụ def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)2 from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)51 tương đương với from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)49, đến lượt nó tương đương với from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)53, là gốc của hệ thống phân cấp siêu dữ liệu của Python Mới trong phiên bản 3. 5. 2 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . đang gõ. Chữ Loại có thể được sử dụng để chỉ báo cho người kiểm tra loại rằng tham số hàm hoặc biến tương ứng có giá trị tương đương với chữ được cung cấp (hoặc một trong số nhiều chữ). Ví dụ def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)3 from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)56 không thể được phân lớp. Trong thời gian chạy, một giá trị tùy ý được phép làm đối số kiểu cho from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)56, nhưng bộ kiểm tra kiểu có thể áp đặt các hạn chế. Xem PEP 586 để biết thêm chi tiết về các loại chữ Mới trong phiên bản 3. 8 Đã thay đổi trong phiên bản 3. 9. 1. ______1_______40 hiện loại bỏ các tham số trùng lặp. So sánh bình đẳng của Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])40 đối tượng không còn phụ thuộc vào thứ tự. Các đối tượng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])40 giờ đây sẽ đưa ra một ngoại lệ trong quá trình so sánh bằng nếu một trong các tham số của chúng không. đang gõ. ClassVar Cấu trúc kiểu đặc biệt để đánh dấu các biến lớp Như đã giới thiệu trong PEP 526, một chú thích biến được bao bọc trong ClassVar cho biết rằng một thuộc tính nhất định được dự định sử dụng làm biến lớp và không được đặt trên các phiên bản của lớp đó. Cách sử dụng def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)4 chỉ chấp nhận các loại và không thể đăng ký thêm bản thân nó không phải là một lớp và không nên được sử dụng với hoặc. không thay đổi hành vi thời gian chạy Python, nhưng nó có thể được sử dụng bởi trình kiểm tra loại của bên thứ ba. Ví dụ: trình kiểm tra loại có thể gắn cờ mã sau đây là lỗi def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)5 Mới trong phiên bản 3. 5. 3 đang gõ. Cuối cùngMột cấu trúc gõ đặc biệt để chỉ ra cho người kiểm tra loại rằng một tên không thể được gán lại hoặc ghi đè trong một lớp con. Ví dụ def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)6 Không có kiểm tra thời gian chạy của các thuộc tính này. Xem PEP 591 để biết thêm chi tiết Mới trong phiên bản 3. 8 đang gõ. Bắt buộcđang gõ. Không bắt buộcCác cấu trúc gõ đặc biệt đánh dấu các phím riêng lẻ của a là bắt buộc hoặc không bắt buộc tương ứng Xem và PEP 655 để biết thêm chi tiết Mới trong phiên bản 3. 11 typing. Chú thíchMột loại, được giới thiệu trong PEP 593 (_______12_______69), để trang trí các loại hiện có với siêu dữ liệu theo ngữ cảnh cụ thể (có thể là nhiều phần của nó, vì Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])44 là biến thể). Cụ thể, loại from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...03 có thể được chú thích bằng siêu dữ liệu from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)72 thông qua gợi ý đánh máy from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)73. Siêu dữ liệu này có thể được sử dụng cho phân tích tĩnh hoặc trong thời gian chạy. Nếu một thư viện (hoặc công cụ) gặp một gợi ý đánh máy from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)73 và không có logic đặc biệt nào cho siêu dữ liệu from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)72, thì thư viện đó nên bỏ qua nó và chỉ coi loại đó là from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...03. Không giống như chức năng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)77 hiện có trong mô-đun Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25 vô hiệu hóa hoàn toàn các chú thích kiểm tra đánh máy trên một hàm hoặc một lớp, loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])44 cho phép cả kiểm tra đánh máy tĩnh của from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...03 (có thể bỏ qua from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)72 một cách an toàn) cùng với quyền truy cập thời gian chạy tới from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)72 trong một ứng dụng cụ thể Cuối cùng, trách nhiệm về cách diễn giải các chú thích (nếu có) là trách nhiệm của công cụ hoặc thư viện gặp phải loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])44. Một công cụ hoặc thư viện gặp loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])44 có thể quét qua các chú thích để xác định xem chúng có đáng quan tâm hay không (e. g. , sử dụng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)64) When a tool or a library does not support annotations or encounters an unknown annotation it should just ignore it and treat annotated type as the underlying type It’s up to the tool consuming the annotations to decide whether the client is allowed to have several annotations on one type and how to merge those annotations Vì loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])44 cho phép bạn đặt một số chú thích cùng (hoặc khác) loại trên bất kỳ nút nào, các công cụ hoặc thư viện sử dụng các chú thích đó chịu trách nhiệm xử lý các bản sao tiềm ẩn. Ví dụ: nếu bạn đang thực hiện phân tích phạm vi giá trị, bạn có thể cho phép điều này def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)7 Đi qua from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)87 để cho phép một người truy cập các chú thích bổ sung khi chạy The details of the syntax
Mới trong phiên bản 3. 9 đang gõ. TypeGuardSpecial typing form used to annotate the return type of a user-defined type guard function. Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])52 only accepts a single type argument. Khi chạy, các hàm được đánh dấu theo cách này sẽ trả về một giá trị boolean Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])52 aims to benefit type narrowing – a technique used by static type checkers to determine a more precise type of an expression within a program’s code flow. Thông thường, việc thu hẹp loại được thực hiện bằng cách phân tích luồng mã có điều kiện và áp dụng việc thu hẹp cho một khối mã. Biểu thức điều kiện ở đây đôi khi được gọi là "loại bảo vệ" # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)3 Đôi khi sẽ thuận tiện khi sử dụng hàm boolean do người dùng định nghĩa làm bộ bảo vệ kiểu. Một chức năng như vậy nên sử dụng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)97 làm kiểu trả về của nó để cảnh báo những người kiểm tra kiểu tĩnh về ý định này Sử dụng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)98 báo cho trình kiểm tra kiểu tĩnh rằng đối với một chức năng nhất định
Ví dụ # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)4 Nếu def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)01 là một phương thức lớp hoặc thể hiện, thì kiểu trong Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])52 ánh xạ tới kiểu của tham số thứ hai sau from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...78 hoặc def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)04 Nói tóm lại, dạng def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)05, có nghĩa là nếu def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)06 trả về from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)99, thì def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)08 thu hẹp từ def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)09 thành def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)10 Ghi chú def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)10 không nhất thiết phải là dạng hẹp hơn của def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)09 – nó thậm chí có thể là dạng rộng hơn. The main reason is to allow for things like narrowing def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)13 to def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)14 even though the latter is not a subtype of the former, since def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)15 is invariant. Trách nhiệm viết các bộ bảo vệ loại an toàn thuộc về người dùng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])52 cũng hoạt động với các biến kiểu. Xem PEP 647 để biết thêm chi tiết New in version 3. 10 Building generic typesChúng không được sử dụng trong chú thích. Họ đang xây dựng các khối để tạo các loại chung class typing. GenericAbstract base class for generic types A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)5 This class can then be used as follows # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)6class typing. TypeVar Type variable Usage # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)7 Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See for more information on generic types. Generic functions work as follows # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)8 Note that type variables can be bound, constrained, or neither, but cannot be both bound and constrained Bound type variables and constrained type variables have different semantics in several important ways. Using a bound type variable means that the Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])29 will be solved using the most specific type possible # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)9 Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass0 Using a constrained type variable, however, means that the Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])29 can only ever be solved as being exactly one of the constraints given from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass1 At runtime, def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)20 will raise . In general, and should not be used with types Type variables may be marked covariant or contravariant by passing def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)24 or def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)25. See PEP 484 for more details. By default, type variables are invariantclass typing. TypeVarTuple Type variable tuple. A specialized form of that enables variadic generics A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an arbitrary number of types by acting like an arbitrary number of type variables wrapped in a tuple. For example from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass2 Note the use of the unpacking operator def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)27 in def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)28. Conceptually, you can think of def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)29 as a tuple of type variables def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)30. def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)28 would then become def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)32, which is equivalent to def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)33. (Note that in older versions of Python, you might see this written using instead, as def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)35. ) Type variable tuples must always be unpacked. This helps distinguish type variable tuples from normal type variables from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass3 Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass4 Type variable tuples can be happily combined with normal type variables from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass5 However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass6 Finally, an unpacked type variable tuple can be used as the type annotation of def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)36 from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass7 In contrast to non-unpacked annotations of def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)36 - e. g. def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)38, which would specify that all arguments are Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])63 - def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)40 enables reference to the types of the individual arguments in def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)36. Here, this allows us to ensure the types of the def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)36 passed to def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)43 match the types of the (positional) arguments of def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)44 See PEP 646 for more details on type variable tuples Mới trong phiên bản 3. 11 typing. UnpackA typing operator that conceptually marks an object as having been unpacked. For example, using the unpack operator def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)27 on a is equivalent to using def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)34 to mark the type variable tuple as having been unpacked from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass8 In fact, def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)34 can be used interchangeably with def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)27 in the context of types. You might see def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)34 being used explicitly in older versions of Python, where def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)27 couldn’t be used in certain places from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass9 Mới trong phiên bản 3. 11 class typing. ParamSpec(name , * , bound=None , covariant=False , contravariant=False)Parameter specification variable. A specialized version of Usage from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)0 Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable – a pattern commonly found in higher order functions and decorators. They are only valid when used in Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])49, or as the first argument to Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])28, or as parameters for user-defined Generics. See for more information on generic types For example, to add basic logging to a function, one can create a decorator def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)56 to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)1 Without Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])48, the simplest way to annotate this previously was to use a with bound from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)09. However this causes two problems
Since Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])48 captures both positional and keyword parameters, def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)69 and def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)70 can be used to split a Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])48 into its components. def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)69 represents the tuple of positional parameters in a given call and should only be used to annotate def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)36. def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)70 represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)62. Both attributes require the annotated parameter to be in scope. At runtime, def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)69 and def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)70 are instances respectively of and Parameter specification variables created with def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)24 or def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)25 can be used to declare covariant or contravariant generic types. The def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)82 argument is also accepted, similar to . However the actual semantics of these keywords are yet to be decided New in version 3. 10 Ghi chú Only parameter specification variables defined in global scope can be pickled See also
Arguments and keyword arguments attributes of a . The def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)69 attribute of a Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])48 is an instance of def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)78, and def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)70 is an instance of def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)79. They are intended for runtime introspection and have no special meaning to static type checkers Calling on either of these objects will return the original Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])48 from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)2 New in version 3. 10 typing. AnyStrdef get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)96 is a defined as def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)98 It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)3class typing. Protocol(Generic) Base class for protocol classes. Protocol classes are defined like this from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)4 Các lớp như vậy chủ yếu được sử dụng với các trình kiểm tra kiểu tĩnh nhận biết kiểu con cấu trúc (gõ vịt tĩnh), chẳng hạn from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)5 Xem PEP 544 để biết thêm chi tiết. Protocol classes decorated with (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures Protocol classes can be generic, for example from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)6 Mới trong phiên bản 3. 8 @typing. runtime_checkableMark a protocol class as a runtime protocol Such a protocol can be used with and . Điều này tăng lên khi áp dụng cho một lớp phi giao thức. Điều này cho phép kiểm tra cấu trúc đơn giản, rất giống với “one trick pony” chẳng hạn như. For example from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)7 Ghi chú sẽ chỉ kiểm tra sự hiện diện của các phương thức được yêu cầu, không phải chữ ký loại của chúng. Ví dụ, là một lớp, do đó nó vượt qua kiểm tra đối với. However, the # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)09 method exists only to raise a with a more informative message, therefore making it impossible to call (instantiate) Mới trong phiên bản 3. 8 Các chỉ thị đặc biệt khácChúng không được sử dụng trong chú thích. Họ đang xây dựng các khối để khai báo các loại class typing. NamedTuplePhiên bản đánh máy của Usage from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)8 Điều này tương đương với from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)9 To give a field a default value, you can assign to it in the class body from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update0 Các trường có giá trị mặc định phải xuất hiện sau bất kỳ trường nào không có giá trị mặc định Lớp kết quả có một thuộc tính bổ sung # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)13 đưa ra một lệnh ánh xạ tên trường với các loại trường. (Tên trường nằm trong thuộc tính # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)14 và giá trị mặc định nằm trong thuộc tính # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)15, cả hai đều là một phần của API. ) # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)17 lớp con cũng có thể có chuỗi tài liệu và phương thức from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update1 # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)17 lớp con có thể chung chung from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update2 Sử dụng tương thích ngược from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update3 Đã thay đổi trong phiên bản 3. 6. Added support for PEP 526 variable annotation syntax. Đã thay đổi trong phiên bản 3. 6. 1. Đã thêm hỗ trợ cho các giá trị, phương thức và chuỗi tài liệu mặc định. Đã thay đổi trong phiên bản 3. 8. Các thuộc tính # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)19 và # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)13 hiện là từ điển thông thường thay vì phiên bản của # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)21. Đã thay đổi trong phiên bản 3. 9. Removed the # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)19 attribute in favor of the more standard # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)13 attribute which has the same information. Đã thay đổi trong phiên bản 3. 11. Đã thêm hỗ trợ cho các bộ có tên chung. lớp đang gõ. Kiểu mới(tên , tp)Một lớp trợ giúp để chỉ ra một loại khác biệt cho trình đánh máy, xem. Khi chạy, nó trả về một đối tượng trả về đối số của nó khi được gọi. Cách sử dụng from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update4 Mới trong phiên bản 3. 5. 2 Đã thay đổi trong phiên bản 3. 10. ______1_______62 bây giờ là một lớp chứ không phải là một hàm. lớp đang gõ. TypedDict(dict)Special construct to add type hints to a dictionary. Trong thời gian chạy nó là một đồng bằng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Cách sử dụng from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update5 Để cho phép sử dụng tính năng này với các phiên bản Python cũ hơn không hỗ trợ PEP 526, Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 hỗ trợ thêm hai dạng cú pháp tương đương
Không dùng nữa kể từ phiên bản 3. 11, sẽ bị xóa trong phiên bản 3. 13. Cú pháp đối số từ khóa không được dùng trong 3. 11 và sẽ bị xóa trong 3. 13. It may also be unsupported by static type checkers. The functional syntax should also be used when any of the keys are not valid , for example because they are keywords or contain hyphens. Thí dụ from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update8 Theo mặc định, tất cả các khóa phải có trong một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41. Có thể đánh dấu các khóa riêng lẻ là không bắt buộc bằng cách sử dụng from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update9 This means that a # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)31 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 can have the # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)33 key omitted Cũng có thể đánh dấu tất cả các khóa là không bắt buộc theo mặc định bằng cách chỉ định tổng số là # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)34 from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...0 This means that a # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)31 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 can have any of the keys omitted. A type checker is only expected to support a literal # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)34 or from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)99 as the value of the # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)39 argument. from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)99 is the default, and makes all items defined in the class body required Individual keys of a # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)41 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 can be marked as required using from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...1 Loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 có thể kế thừa từ một hoặc nhiều loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 khác bằng cách sử dụng cú pháp dựa trên lớp. Cách sử dụng from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...2 # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)46 has three items. from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)72, # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)48 và # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)49. Nó tương đương với định nghĩa này from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...3 Một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 không thể kế thừa từ một lớp không phải ______1_______41, ngoại trừ. Ví dụ from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...4 A Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 can be generic from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...5 Có thể xem xét nội quan một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 thông qua các lệnh chú thích (xem để biết thêm thông tin về các phương pháp hay nhất về chú thích), , , và__toàn bộ__ # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)58 đưa ra giá trị của đối số # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)39. Example from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...6__required_keys__ Mới trong phiên bản 3. 9 __optional_keys__# 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)60 and # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)61 return objects containing required and non-required keys, respectively Các khóa được đánh dấu bằng sẽ luôn xuất hiện trong # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)56 và các khóa được đánh dấu bằng sẽ luôn xuất hiện trong # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)57 For backwards compatibility with Python 3. 10 trở xuống, cũng có thể sử dụng tính kế thừa để khai báo cả khóa bắt buộc và khóa không bắt buộc trong cùng một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41. Điều này được thực hiện bằng cách khai báo một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 với một giá trị cho đối số # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)39 và sau đó kế thừa từ nó trong một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 khác với một giá trị khác cho # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)39 from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...7 Mới trong phiên bản 3. 9 See PEP 589 for more examples and detailed rules of using Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41 Mới trong phiên bản 3. 8 Đã thay đổi trong phiên bản 3. 11. Đã thêm hỗ trợ để đánh dấu các khóa riêng lẻ là hoặc. Xem PEP 655. Đã thay đổi trong phiên bản 3. 11. Added support for generic Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])41s. Bộ sưu tập bê tông chungTương ứng với các loại tích hợpclass typing. Dict(dict, MutableMapping[KT, VT])Một phiên bản chung của. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nên sử dụng loại bộ sưu tập trừu tượng, chẳng hạn như Loại này có thể được sử dụng như sau from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...8 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Danh sách(danh sách, MutableSequence[T]) Phiên bản chung của. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nên sử dụng một loại tập hợp trừu tượng như hoặc Loại này có thể được sử dụng như sau from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ...9 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Set(set, MutableSet[T]) Một phiên bản chung của. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nên sử dụng loại bộ sưu tập trừu tượng, chẳng hạn như Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. FrozenSet(frozenset, AbstractSet[T_co]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . Ghi chú là một hình thức đặc biệt Tương ứng với các loại tronglớp đang gõ. DefaultDict(bộ sưu tập. defaultdict, MutableMapping[KT, VT])Một phiên bản chung của Mới trong phiên bản 3. 5. 2 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. OrderedDict(bộ sưu tập. OrderedDict, MutableMapping[KT, VT]) Một phiên bản chung của Mới trong phiên bản 3. 7. 2 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Bản đồ chuỗi(bộ sưu tập. ChainMap, MutableMapping[KT, VT]) Một phiên bản chung của New in version 3. 5. 4 Mới trong phiên bản 3. 6. 1 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Bộ đếm(bộ sưu tập. Bộ đếm, Dict[T, int]) Một phiên bản chung của New in version 3. 5. 4 Mới trong phiên bản 3. 6. 1 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Deque(deque, MutableSequence[T]) Một phiên bản chung của New in version 3. 5. 4 Mới trong phiên bản 3. 6. 1 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . Các loại bê tông kháclớp đang gõ. IOclass typing. TextIOlớp đang gõ. Nhị phânIOLoại chung from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass09 và các lớp con của nó from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass10 và from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass11 đại diện cho các loại luồng I/O chẳng hạn như được trả về bởi Không dùng nữa kể từ phiên bản 3. 8, sẽ bị xóa trong phiên bản 3. 13. Không gian tên from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass13 không được dùng nữa và sẽ bị xóa. Thay vào đó, các loại này nên được nhập trực tiếp từ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25. lớp đang gõ. Mẫulớp gõ. Trận đấu Các bí danh loại này tương ứng với các loại trả về từ và. Các loại này (và các chức năng tương ứng) là chung chung trong def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)96 và có thể được cụ thể hóa bằng cách viết from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass18, from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass19, from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass20 hoặc from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass21 Không dùng nữa kể từ phiên bản 3. 8, sẽ bị xóa trong phiên bản 3. 13. Không gian tên from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass22 không được dùng nữa và sẽ bị xóa. Thay vào đó, các loại này nên được nhập trực tiếp từ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25. Không dùng nữa kể từ phiên bản 3. 9. Các lớp from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass24 và from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass25 từ bây giờ sẽ hỗ trợ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57. See PEP 585 and . lớp đang gõ. Text from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass28 is an alias for Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])33. Nó được cung cấp để cung cấp đường dẫn tương thích chuyển tiếp cho mã Python 2. trong Python 2, from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass28 là bí danh của from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass31 Sử dụng from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass28 để chỉ ra rằng một giá trị phải chứa chuỗi unicode theo cách tương thích với cả Python 2 và Python 3 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])00 Mới trong phiên bản 3. 5. 2 Không dùng nữa kể từ phiên bản 3. 11. Python 2 không còn được hỗ trợ và hầu hết các trình kiểm tra kiểu cũng không còn hỗ trợ kiểm tra kiểu mã Python 2. Việc xóa bí danh hiện chưa được lên kế hoạch, nhưng người dùng được khuyến khích sử dụng thay vì from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass28 bất cứ khi nào có thể. Các lớp cơ sở trừu tượngTương ứng với các bộ sưu tập tronglớp đang gõ. AbstractSet(Collection[T_co])Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. ByteString(Sequence[int]) Một phiên bản chung của This type represents the types , , and of byte sequences Là cách viết tắt của loại này, có thể được sử dụng để chú thích đối số của bất kỳ loại nào được đề cập ở trên Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Bộ sưu tập(Có kích thước, Có thể lặp lại[T_co], Container[T_co]) Một phiên bản chung của Mới trong phiên bản 3. 6. 0 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Vùng chứa(Chung[T_co]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. KeysView(MappingView, AbstractSet[KT_co]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . class typing. Ánh xạ(Bộ sưu tập[KT], Chung[KT, VT_co]) Một phiên bản chung của. This type can be used as follows Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])01 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Chế độ xem bản đồ(Đã định cỡ) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. MutableMapping(Mapping[KT, VT]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Sequence có thể thay đổi(Sequence[T]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . class typing. MutableSet(AbstractSet[T]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Sequence(Reversible[T_co], Collection[T_co]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . Tương ứng với các loại khác tronglớp đang gõ. Iterable(Generic[T_co])Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Iterator(Iterable[T_co]) Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Trình tạo(Iterator[T_co], Chung[T_co, T_contra, V_co]) Trình tạo có thể được chú thích theo loại chung chung from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass86. Ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])02 Note that unlike many other generics in the typing module, the from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass87 of behaves contravariantly, not covariantly or invariantly Nếu trình tạo của bạn chỉ mang lại giá trị, hãy đặt from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass87 và from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)07 thành Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])60 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])03 Ngoài ra, hãy chú thích trình tạo của bạn có kiểu trả về là from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass92 hoặc from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass93 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])04 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Có thể băm Một bí danh cho lớp đang gõ. Có thể đảo ngược(Có thể lặp lại[T_co])Một phiên bản chung của Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . class typing. Có kích thước Một bí danh cho Lập trình không đồng bộclass typing. Coroutine(Awaitable[V_co], Chung[T_co, T_contra, V_co])Một phiên bản chung của. Phương sai và thứ tự của các biến loại tương ứng với biến của , ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])05 Mới trong phiên bản 3. 5. 3 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra]) Trình tạo không đồng bộ có thể được chú thích theo loại chung from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)05. Ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])06 Không giống như các trình tạo thông thường, trình tạo không đồng bộ không thể trả về giá trị, vì vậy không có tham số loại from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)07. Như với , from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass87 hoạt động trái ngược Nếu trình tạo của bạn chỉ mang lại giá trị, hãy đặt from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass87 thành Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])60 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])07 Ngoài ra, hãy chú thích trình tạo của bạn có kiểu trả về là from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)11 hoặc from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)12 Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])08 Mới trong phiên bản 3. 6. 1 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. AsyncIterable(Chung[T_co]) Một phiên bản chung của Mới trong phiên bản 3. 5. 2 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. AsyncIterator(AsyncIterable[T_co]) Một phiên bản chung của Mới trong phiên bản 3. 5. 2 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. Có thể chờ đợi(Chung[T_co]) Một phiên bản chung của Mới trong phiên bản 3. 5. 2 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . Các loại trình quản lý bối cảnhlớp đang gõ. Trình quản lý bối cảnh(Chung[T_co])Một phiên bản chung của New in version 3. 5. 4 Mới trong phiên bản 3. 6. 0 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . lớp đang gõ. AsyncContextManager(Chung[T_co]) Một phiên bản chung của New in version 3. 5. 4 Mới trong phiên bản 3. 6. 2 Deprecated since version 3. 9. now supports subscripting ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...57). See PEP 585 and . giao thứcCác giao thức này được trang trí với lớp đang gõ. Hỗ trợ AbsMột ABC với một phương thức trừu tượng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)31 đồng biến trong kiểu trả về của nólớp đang gõ. Số byte hỗ trợ Một ABC với một phương pháp trừu tượng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)32lớp đang gõ. Hỗ trợ Phức hợp Một ABC với một phương pháp trừu tượng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)33lớp đang gõ. Hỗ trợFloat Một ABC với một phương pháp trừu tượng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)34lớp đang gõ. Chỉ số hỗ trợ Một ABC với một phương pháp trừu tượng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)35 Mới trong phiên bản 3. 8 lớp đang gõ. Hỗ trợIntMột ABC với một phương pháp trừu tượng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)36lớp đang gõ. Vòng hỗ trợ Một ABC với một phương thức trừu tượng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)37 đồng biến trong kiểu trả về của nó Functions and decoratorsđang gõ. truyền(typ , val)Truyền một giá trị cho một loại Điều này trả về giá trị không thay đổi. Đối với trình kiểm tra loại, điều này báo hiệu rằng giá trị trả về có loại được chỉ định, nhưng trong thời gian chạy, chúng tôi cố tình không kiểm tra bất kỳ thứ gì (chúng tôi muốn điều này càng nhanh càng tốt) đang gõ. assert_type(val , typ, /)Yêu cầu trình kiểm tra loại tĩnh xác nhận rằng val có loại được suy luận Khi trình kiểm tra loại gặp lệnh gọi tới from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)38, nó sẽ báo lỗi nếu giá trị không thuộc loại đã chỉ định Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])09 Khi chạy, điều này trả về đối số đầu tiên không thay đổi mà không có tác dụng phụ Chức năng này hữu ích để đảm bảo sự hiểu biết của trình kiểm tra loại về tập lệnh phù hợp với ý định của nhà phát triển Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])10 Mới trong phiên bản 3. 11 đang gõ. assert_never(arg , /)Yêu cầu trình kiểm tra loại tĩnh xác nhận rằng một dòng mã không thể truy cập được Thí dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])11 Ở đây, các chú thích cho phép trình kiểm tra loại suy luận rằng trường hợp cuối cùng không bao giờ có thể thực thi, bởi vì def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)08 là an hoặc a và cả hai tùy chọn đều nằm trong trường hợp trước đó. Nếu trình kiểm tra loại thấy rằng có thể truy cập lệnh gọi tới ____28_______42, nó sẽ phát ra lỗi. Ví dụ: nếu chú thích loại cho def get_user_name(user_id: UserId) -> str: ... # passes type checking user_a = get_user_name(UserId(42351)) # fails type checking; an int is not a UserId user_b = get_user_name(-1)08 thay vì from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)44, trình kiểm tra loại sẽ phát ra lỗi chỉ ra rằng from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)45 là loại. Đối với một cuộc gọi đến ____28_______47 để vượt qua kiểm tra loại, loại suy luận của đối số được truyền vào phải là loại dưới cùng, và không có gì khác Khi chạy, điều này ném một ngoại lệ khi được gọi See also Kiểm tra mức độ đầy đủ và mã không thể truy cập có thêm thông tin về kiểm tra mức độ đầy đủ bằng cách gõ tĩnh Mới trong phiên bản 3. 11 đang gõ. reveal_type(obj , /)Tiết lộ loại tĩnh được suy luận của một biểu thức Khi trình kiểm tra kiểu tĩnh gặp lệnh gọi hàm này, nó sẽ phát ra chẩn đoán với kiểu đối số. Ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])12 Điều này có thể hữu ích khi bạn muốn gỡ lỗi cách trình kiểm tra loại của bạn xử lý một đoạn mã cụ thể Hàm trả về đối số của nó không thay đổi, cho phép sử dụng nó trong một biểu thức Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])13 Hầu hết các trình kiểm tra loại đều hỗ trợ from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)49 ở mọi nơi, ngay cả khi tên không được nhập từ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25. Nhập tên từ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25 cho phép mã của bạn chạy mà không có lỗi thời gian chạy và truyền đạt ý định rõ ràng hơn Trong thời gian chạy, hàm này in kiểu thời gian chạy của đối số của nó thành thiết bị lỗi chuẩn và trả về nó không thay đổi Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])14 Mới trong phiên bản 3. 11 @đang gõ. dataclass_transformcó thể được sử dụng để trang trí một lớp, siêu dữ liệu hoặc một chức năng mà chính nó là một công cụ trang trí. Sự hiện diện của from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)53 cho một trình kiểm tra kiểu tĩnh biết rằng đối tượng được trang trí thực hiện “phép thuật” trong thời gian chạy để biến đổi một lớp, mang lại cho nó các hành vi giống như Example usage with a decorator function Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])15 Trên một lớp cơ sở Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])16 Trên một siêu dữ liệu Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])17 Các lớp from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)55 được xác định ở trên sẽ được xử lý bằng bộ kiểm tra loại tương tự như các lớp được tạo bằng. Ví dụ: bộ kiểm tra loại sẽ cho rằng các lớp này có các phương thức from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)57 chấp nhận from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)58 và Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])32 Lớp, siêu dữ liệu hoặc hàm được trang trí có thể chấp nhận các đối số bool sau đây mà trình kiểm tra loại sẽ cho rằng có tác dụng tương tự như đối với trình trang trí. from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)61, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)62, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)63, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)64, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)65, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)66, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)67 và from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)68. Giá trị của các đối số này (_______12_______99 hoặc # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)34) phải có thể được đánh giá tĩnh Các đối số cho trình trang trí from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId)52 có thể được sử dụng để tùy chỉnh các hành vi mặc định của lớp, siêu dữ liệu hoặc hàm được trang trí
Trình kiểm tra loại nhận ra các đối số tùy chọn sau trên bộ xác định trường
Khi chạy, trình trang trí này ghi lại các đối số của nó trong thuộc tính from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update01 trên đối tượng được trang trí. Nó không có hiệu ứng thời gian chạy khác Xem PEP 681 để biết thêm chi tiết Mới trong phiên bản 3. 11 @đang gõ. quá tảiTrình trang trí from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update02 cho phép mô tả các hàm và phương thức hỗ trợ nhiều kết hợp khác nhau của các loại đối số. Một loạt các định nghĩa được trang trí _ from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update02 phải được theo sau bởi chính xác một định nghĩa không được trang trí ____42_______02 (cho cùng một chức năng/phương thức). Các định nghĩa được trang trí _ from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update02 chỉ dành cho lợi ích của trình kiểm tra loại, vì chúng sẽ bị ghi đè bởi định nghĩa không được trang trí ____42_______02, trong khi định nghĩa sau được sử dụng trong thời gian chạy nhưng nên được trình kiểm tra loại bỏ qua. Trong thời gian chạy, việc gọi trực tiếp một hàm được trang trí from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update02 sẽ tăng. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được biểu thị bằng cách sử dụng liên kết hoặc biến loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])18 Xem PEP 484 để biết thêm chi tiết và so sánh với các ngữ nghĩa đánh máy khác Đã thay đổi trong phiên bản 3. 11. Các chức năng bị quá tải giờ đây có thể được xem xét nội tâm khi chạy bằng cách sử dụng. đang gõ. get_overloads(func)Trả về một chuỗi các định nghĩa -decorated cho func. func là đối tượng chức năng để thực hiện chức năng quá tải. Ví dụ, đưa ra định nghĩa về from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update11 trong tài liệu về , from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update13 sẽ trả về một chuỗi gồm ba đối tượng hàm cho ba lần quá tải đã xác định. Nếu được gọi trên một hàm không có tình trạng quá tải, from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update09 sẽ trả về một chuỗi trống from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update09 có thể được sử dụng để xem xét nội hàm một hàm bị quá tải khi chạy Mới trong phiên bản 3. 11 đang gõ. clear_overloads()Xóa tất cả các quá tải đã đăng ký trong sổ đăng ký nội bộ. Điều này có thể được sử dụng để lấy lại bộ nhớ được sử dụng bởi sổ đăng ký Mới trong phiên bản 3. 11 @đang gõ. cuối cùngMột trình trang trí để chỉ ra cho người kiểm tra loại rằng phương thức được trang trí không thể bị ghi đè và lớp được trang trí không thể được phân lớp. Ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])19 Không có kiểm tra thời gian chạy của các thuộc tính này. Xem PEP 591 để biết thêm chi tiết Mới trong phiên bản 3. 8 Đã thay đổi trong phiên bản 3. 11. Người trang trí bây giờ sẽ đặt thuộc tính from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update16 thành from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)99 trên đối tượng được trang trí. Do đó, một kiểm tra như from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update18 có thể được sử dụng trong thời gian chạy để xác định xem một đối tượng from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update19 đã được đánh dấu là cuối cùng hay chưa. Nếu đối tượng được trang trí không hỗ trợ cài đặt thuộc tính, trình trang trí sẽ trả về đối tượng không thay đổi mà không đưa ra ngoại lệ. @đang gõ. no_type_check Trình trang trí để chỉ ra rằng các chú thích không phải là gợi ý loại Điều này hoạt động như lớp hoặc chức năng. Với một lớp, nó áp dụng đệ quy cho tất cả các phương thức và lớp được định nghĩa trong lớp đó (nhưng không áp dụng cho các phương thức được định nghĩa trong lớp cha hoặc lớp con của nó) Điều này làm thay đổi (các) chức năng tại chỗ @đang gõ. no_type_check_decoratorTrang trí để cung cấp cho một trang trí khác hiệu ứng Điều này bao bọc trình trang trí bằng thứ gì đó bao bọc chức năng được trang trí trong @đang gõ. type_check_onlyTrình trang trí để đánh dấu một lớp hoặc chức năng không khả dụng khi chạy Bản thân trình trang trí này không có sẵn trong thời gian chạy. Nó chủ yếu nhằm đánh dấu các lớp được định nghĩa trong các tệp sơ khai kiểu nếu việc triển khai trả về một thể hiện của một lớp riêng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])20 Lưu ý rằng không nên trả lại các phiên bản của các lớp riêng tư. Tốt nhất là công khai các lớp như vậy người trợ giúp nội tâmđang gõ. get_type_hints(obj , globalns=None, localns=None, include_extras=False)Trả về một từ điển chứa các gợi ý kiểu cho một hàm, phương thức, mô-đun hoặc đối tượng lớp Điều này thường giống như from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update22. Ngoài ra, các tham chiếu chuyển tiếp được mã hóa dưới dạng chuỗi ký tự được xử lý bằng cách đánh giá chúng trong các không gian tên from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update23 và from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update24. Đối với lớp from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)41, trả về một từ điển được xây dựng bằng cách hợp nhất tất cả các ____20_______13 dọc theo ____42_______27 theo thứ tự ngược lại Hàm thay thế đệ quy tất cả from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update28 bằng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...03, trừ khi from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update30 được đặt thành from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)99 (xem để biết thêm thông tin). Ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])21 Ghi chú không hoạt động với nhập bao gồm các tham chiếu chuyển tiếp. Cho phép đánh giá chú thích bị trì hoãn (PEP 563) có thể loại bỏ nhu cầu đối với hầu hết các tham chiếu chuyển tiếp Đã thay đổi trong phiên bản 3. 9. Đã thêm tham số from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update30 như một phần của PEP 593. Đã thay đổi trong phiên bản 3. 11. Trước đây, from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update35 đã được thêm vào cho các chú thích hàm và phương thức nếu giá trị mặc định bằng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])60 được đặt. Bây giờ chú thích được trả lại không thay đổi. đang gõ. get_args(tp)đang gõ. get_origin(tp) Cung cấp nội quan cơ bản cho các loại chung và các hình thức gõ đặc biệt Đối với một đối tượng gõ có dạng from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update37, các hàm này trả về from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update38 và from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update39. Nếu from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update38 là bí danh chung cho nội trang hoặc lớp, nó sẽ được chuẩn hóa thành lớp ban đầu. Nếu from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update38 là một liên kết hoặc được chứa trong một loại chung khác, thứ tự của from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update39 có thể khác với thứ tự của các đối số ban đầu from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update45 do bộ nhớ đệm loại. Đối với các đối tượng không được hỗ trợ, hãy trả lại tương ứng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])60 và from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update47. ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])22 Mới trong phiên bản 3. 8 đang gõ. được đánh máy(đến)Kiểm tra xem một loại có phải là một Ví dụ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])23 New in version 3. 10 lớp đang gõ. ForwardRefA class used for internal typing representation of string forward references. Ví dụ: from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update49 được chuyển đổi ngầm thành from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update50. Lớp này không nên được khởi tạo bởi người dùng, nhưng có thể được sử dụng bởi các công cụ hướng nội Ghi chú Các loại chung PEP 585 chẳng hạn như from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update51 sẽ không được chuyển đổi hoàn toàn thành from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update52 và do đó sẽ không tự động phân giải thành from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update53 Mới trong phiên bản 3. 7. 4 Hằng sốđang gõ. TYPE_CHECKINGMột hằng số đặc biệt được giả định là from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)99 bởi trình kiểm tra loại tĩnh của bên thứ 3. Đó là # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)34 trong thời gian chạy. Cách sử dụng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])24 Chú thích loại đầu tiên phải được đặt trong dấu ngoặc kép, làm cho nó trở thành "tham chiếu chuyển tiếp", để ẩn tham chiếu from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update56 khỏi thời gian chạy trình thông dịch. Loại chú thích cho các biến cục bộ không được đánh giá, vì vậy chú thích thứ hai không cần phải được đặt trong dấu ngoặc kép Ghi chú Nếu sử dụng from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update57, các chú thích sẽ không được đánh giá tại thời điểm định nghĩa hàm. Thay vào đó, chúng được lưu trữ dưới dạng chuỗi trong # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)13. Điều này làm cho việc sử dụng dấu ngoặc kép xung quanh chú thích là không cần thiết (xem PEP 563) Mới trong phiên bản 3. 5. 2 Dòng thời gian ngừng sử dụng các tính năng chínhMột số tính năng trong Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25 không được dùng nữa và có thể bị xóa trong phiên bản tương lai của Python. Bảng sau đây tóm tắt các loại bỏ chính để thuận tiện cho bạn. Điều này có thể thay đổi và không phải tất cả các phản đối đều được liệt kê Làm thế nào để Python phát hiện gõ?Để lấy kiểu của một biến trong Python, bạn có thể sử dụng hàm type() tích hợp sẵn . Trong Python, mọi thứ đều là đối tượng. Vì vậy, khi bạn sử dụng hàm type() để in loại giá trị được lưu trữ trong một biến ra bàn điều khiển, nó sẽ trả về loại lớp của đối tượng.
How does type checking work?Kiểm tra loại là quá trình xác minh và thực thi các ràng buộc về loại trong giá trị . Trình biên dịch phải kiểm tra xem chương trình nguồn có tuân theo các quy ước về cú pháp và ngữ nghĩa của ngôn ngữ nguồn hay không và nó cũng phải kiểm tra các quy tắc loại của ngôn ngữ đó.
How to check data type in Python?Làm thế nào để bạn có được typeof trong Python? . Trong Python, mọi thứ đều là đối tượng. Do đó, khi bạn sử dụng hàm type() để in loại giá trị của một biến ra bàn điều khiển, nó sẽ trả về loại lớp của đối tượng. use the built-in type() function. In Python, everything is an object. As a result, when you use the type() function to print the type of a variable's value to the console, it returns the class type of the object.
Is typing enforced in Python?The Python runtime does not enforce function and variable type annotations . They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime support for type hints. |