Hướng dẫn typevar python - trăn typevar

Mới trong phiên bản 3.5.

Mã nguồn: lib/gõ.py Lib/typing.py

Ghi chú

Thời gian chạy Python không thực thi chức năng và chú thích loại biến. Chúng có thể được sử dụng bởi các công cụ của bên thứ ba như trình kiểm tra loại, IDE, linter, v.v.


Mô -đun này cung cấp hỗ trợ thời gian chạy cho các gợi ý loại. Hỗ trợ cơ bản nhất bao gồm các 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])
24,
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,
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])
26,
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])
27 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])
28. Để biết thông số kỹ thuật đầy đủ, vui lòng xem PEP 484. Để có phần giới thiệu đơn giản về các gợi ý loại, xem PEP 483.PEP 484. For a simplified introduction to type hints, see PEP 483.

Hàm bên dưới lấy và trả về một chuỗi và được chú thích như sau:

def greeting(name: str) -> str:
    return 'Hello ' + name

Trong hàm

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, đối 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])
30 dự kiến ​​sẽ thuộc 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])
31 và loại trả 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])
31. Các kiểu con được chấp nhận là đối số.

Các tính năng mới thường được thêm vào 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])
33. Gói typing_extensions cung cấp các bản sao của các tính năng mới này cho các phiên bản Python cũ hơn.

Để biết tóm tắt các tính năng không dùng nữa và dòng thời gian không dùng nữa, vui lòng xem dòng thời gian không dùng nữa của các tính năng chính.

Xem thêm

Tài liệu tại https://typing.readthedocs.io/ làm tài liệu tham khảo hữu ích cho các tính năng hệ thống loại, gõ các công cụ liên quan hữu ích và gõ các thực tiễn tốt nhất.

Peps¶ có liên quan

Kể từ khi giới thiệu ban đầu các gợi ý loại trong PEP 484 và PEP 483, một số PEP đã sửa đổi và tăng cường khung Python tựa cho các chú thích loại. Bao gồm các:PEP 484 and PEP 483, a number of PEPs have modified and enhanced Python’s framework for type annotations. These include:

  • PEP 526: Cú pháp để chú thích biến: Syntax for Variable Annotations

    Giới thiệu cú pháp để chú thích các biến bên ngoài định nghĩa hàm 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])
    
    34

  • PEP 544: Các giao thức: Substing cấu trúc (gõ vịt tĩnh): Protocols: Structural subtyping (static duck typing)

    Giới thiệ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])
    
    35 và người trang trí
    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])
    
    36

  • PEP 585: Loại Generics Generics trong các bộ sưu tập tiêu chuẩn: Type Hinting Generics In Standard Collections

    Giới thiệ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])
    
    37 và khả năng sử dụng các lớp thư viện tiêu chuẩn làm loại chunggeneric types

  • PEP 586: Các loại nghĩa đen: Literal Types

    Giới thiệ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])
    
    38

  • PEP 589: TypedDict: Loại gợi ý cho từ điển với một bộ khóa cố định: TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys

    Giới thiệ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])
    
    39

  • PEP 591: Thêm một vòng loại cuối cùng để đánh máy: Adding a final qualifier to typing

    Giới thiệ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])
    
    40 và người trang trí
    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

  • PEP 593: Chức năng linh hoạt và Chú thích thay đổi: Flexible function and variable annotations

    Giới thiệ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])
    
    42

  • PEP 604: Cho phép viết các loại liên minh 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])
    
    43
    : Allow writing union types 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])
    
    43

    Giới thiệ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])
    
    44 và khả năng sử dụng toán tử nhị phâ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])
    
    45 để biểu thị sự kết hợp của các loạiunion of types

  • PEP 612: Biến đặc tả tham số: Parameter Specification Variables

    Giới thiệ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])
    
    46 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])
    
    47

  • PEP 613: Bí danh loại rõ ràng: Explicit Type Aliases

    Giới thiệ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])
    
    48

  • PEP 646: Generics Variadic: Variadic Generics

    Giới thiệ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])
    
    49

  • PEP 647: Người bảo vệ loại do người dùng xác định: User-Defined Type Guards

    Giới thiệ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])
    
    50

  • PEP 655: Đánh dấu các mục cá nhân đánh máy theo yêu cầu hoặc có khả năng bị thiếu: Marking individual TypedDict items as required or potentially missing

    Giới thiệ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])
    
    51 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])
    
    52

  • PEP 673: Loại tự: Self type

    Giới thiệ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])
    
    53

  • PEP 675: Loại chuỗi theo nghĩa đen tùy ý: Arbitrary Literal String Type

    Giới thiệ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])
    
    54

  • PEP 681: Biến đổi lớp dữ liệu: Data Class Transforms

    Giới thiệ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])
    
    55 Trang trí

Gõ bí danh

Một bí danh loại được xác định bằng cách gán loại cho bí danh. Trong ví dụ này,

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 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])
57 sẽ được coi là từ đồng nghĩa có thể hoán đổi cho nhau:

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])

Bí danh loại rất hữu ích để đơn giản hóa chữ ký loại phức. 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:
    ...

Lưu ý rằ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])
58 dưới dạng gợi ý loại là một trường hợp đặc biệt và được thay thế 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])
59.

Kiểu mới¶

Sử dụng Trình trợ giúp

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 để tạo các loại khác nhau:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)

Trình kiểm tra loại tĩnh sẽ xử lý loại mới như thể nó là một lớp con của loại ban đầu. Điều này rất hữu ích trong việc giúp bắt các lỗi logic:

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)

Bạn vẫn có thể thực hiện tất cả các hoạ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])
61 trên một biến 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])
62, nhưng kết quả sẽ luôn luôn thuộc 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])
61. Điều này cho phép bạn vượt qua 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])
62 bất cứ nơi nà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])
61 có thể được mong đợi, nhưng sẽ ngăn bạn vô tình tạo ra
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 theo cách không hợp lệ:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)

Lưu ý rằng các kiểm tra này chỉ được thực thi bởi trình kiểm tra loại tĩnh. Trong thời gian chạy, câu lệ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])
67 sẽ biế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])
68 có thể gọi được ngay lập tức trả về bất kỳ tham số nào bạn vượt qua. Điều đó có nghĩa là 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])
69 không tạo ra một lớp mới hoặc giới thiệu nhiều chi phí vượt ra ngoài cuộc gọi chức năng thông thường.

Chính xác hơn, 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])
70 luôn đúng khi chạy.

Nó không hợp lệ khi tạo một loại phụ 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])
68:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass

Tuy nhiên, có thể tạo ra 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])
60 dựa trên 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])
60:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)

và đánh máy cho

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])
74 sẽ hoạt động như mong đợi.

Xem PEP 484 để biết thêm chi tiết.PEP 484 for more details.

Ghi chú

Hãy nhớ lại rằng việc sử dụng một bí danh loại tuyên bố hai loại tương đương với nhau. 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])
75 sẽ làm cho trình kiểm tra loại tĩnh điều trị
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 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])
77 trong mọi trường hợp. Điều này rất 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])
60 tuyên bố một loại là một loại phụ của loại 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])
79 sẽ làm cho trình kiểm tra loại tĩnh xử 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])
68 dưới dạng 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])
77, 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])
77 không thể được sử dụng ở những nơi dự kiến ​​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])
68. Điều này rất hữu ích khi bạn muốn ngăn chặn 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:

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 hiện 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])
60 qua một chức năng thông thường. Tuy nhiên, chi phí này sẽ được giảm trong 3.11.0.
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 now a class rather than a function. There is some additional runtime cost when calling
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 over a regular function. However, this cost will be reduced in 3.11.0.

Gọi là có thể gọi được

Các khung mong đợi các chức năng gọi lại của chữ ký cụ thể có thể được loại gợ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])
86.

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 loại trả về của một cuộc gọi có thể gọi mà không chỉ định chữ ký cuộc gọi bằng cách thay thế một dấu chấm lửng theo nghĩa đen cho danh sách các đối số trong loại 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])
87.

Các thiết bị gọi lấy các thiết bị 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

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])
46. Ngoài ra, nếu có thể gọi được thêm hoặc xóa các đối số khỏi các loại gọi khác, toá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])
47 có thể được sử dụng. Họ lần lượt nhận 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])
90 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])
91.

Thuốc generics;

Vì thông tin loại về các đối tượng được giữ trong các container không thể được suy ra tĩnh một cách 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 yếu tố container.

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 việc gõ 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])
27.

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

Các loại chung do người dùng xác định

Một lớp do người dùng xác định 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

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 Là một lớp cơ sở định nghĩa rằng lớp
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])
94 lấy một tham số loại duy nhấ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])
95. Điều này cũng làm cho
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])
95 có giá trị như một loại trong cơ thể lớp.

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])
28 xác đị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])
98 để
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])
99 hợp lệ dưới dạng 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. Tất cả các giố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])
27 được cho 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 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])
28 phải khác biệt. Điều này 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])
28:

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 loại 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:
    ...
03 có một tham số duy nhấ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])
95.

Sử dụng một lớp chung mà không chỉ định các tham số loại giả đị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])
24 cho mỗi 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:
    ...
06 không chung chung mà là kế thừa ngầm 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:
    ...
07:

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 được xác định của người dùng 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:

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 không còn có Metaclass tùy 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])
28 no longer has a custom metaclass.

Generics do người dùng xác định 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:
    ...
09. Hành vi phù hợp với các biến loại, được mô tả ở trên là các biến đặc tả tham số được coi bởi mô -đun gõ là một biến loại chuyên dụng. 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])
46:

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 chung chỉ có một biến đặc tả tham số sẽ chấp nhận danh sách tham số trong các biểu mẫu

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 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:
    ...
12 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 các chất generic 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])
46 có thể không có chính xá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:
    ...
14 sau khi thay thế trong một số trường hợp vì chúng được dự định chủ yếu để kiểm tra loại tĩnh.

Đã thay đổi trong phiên bản 3.10:

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 hiện có thể được tham số hóa qua các biểu thức tham số. Xem
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])
46 và PEP 612 để biết thêm chi tiế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])
28 can now be parameterized over parameter expressions. See
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])
46 and PEP 612 for more details.

Một lớp chung do người dùng xác định có thể có ABC như các lớp cơ sở mà không có xung đột metaclass. Các metaclass chung không được hỗ trợ. Kết quả của việc chung hóa tham số hóa được lưu trữ và hầu hết các loại trong mô -đun gõ đều có thể băm và có thể so sánh cho sự bình đẳng.

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]) 24

Một loại đặc biệt 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])
24. Một trình kiểm tra loại tĩnh sẽ coi mọi loại là 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])
24 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])
24 là 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ỳ hoạt động hoặc phương thức gọi trên 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])
24 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ị 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])
24 cho loại chính xác hơn. Ví dụ: Trình kiểm tra loại tĩnh đã không báo cá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:
    ...
23 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:
    ...
24 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:
    ...
24 đã được tuyên bố là 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])
31 và nhận được giá trị
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 khi chạy!

Hơn nữa, tất cả các chức năng mà không có loại trả về hoặc loại tham số sẽ mặc định mặc định 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:

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

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 được sử dụng như một hatch thoát ra khi bạn cần trộn mã được gõ linh hoạt và thống kê.

Tương phản hành vi 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])
24 với hành vi 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:
    ...
31. Tương tự 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])
24, mọi loại là một loại phụ 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:
    ...
31. Tuy nhiên, không giống 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])
24, điều ngược lại khô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:
    ...
31 không phải là một kiểu con của mọi loại khác.

Điều đó có nghĩa là khi loại giá trị 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:
    ...
31, trình kiểm tra loại sẽ từ chối hầu hết tất cả các hoạt động trê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 dụng 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

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 để chỉ ra rằng giá trị có thể là bất kỳ loại nào theo cách kiểu an toàn. 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ỉ ra rằng một giá trị được gõ động.

Danh nghĩa so với phân nhóm cấu trúc

Ban đầu PEP 484 xác định hệ thống loại tĩnh Python là sử dụng tiểu mục 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:
    ...
39 được cho phép trong đó 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:
    ...
40 đượ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:
    ...
39 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:
    ...
40.PEP 484 defined the Python static type system as using nominal subtyping. This means that a class
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:
    ...
39 is allowed where a class
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:
    ...
40 is expected if and only if
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:
    ...
39 is a subclass of
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:
    ...
40.

Yêu cầu này trước đây cũng áp dụng cho các lớp cơ sở trừu tượng, chẳng hạn 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:
    ...
43. Vấn đề với phương pháp này là một lớp phải được đánh dấu rõ ràng để hỗ trợ họ, điều này không có âm thanh và không giống như những gì người ta thường làm trong mã python được gõ động một cách tự động. Ví dụ, điều này phù hợp với PEP 484: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 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:
    ...
44 được coi là một loại phụ 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:
    ...
45 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:
    ...
46 bằng trình kiểm tra loại tĩnh. Điều này được gọi là phân nhóm cấu trúc (hoặc gõ vịt tĩnh):
allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowing
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:
    ...
44 to be implicitly considered a subtype of both
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:
    ...
45 and
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:
    ...
46 by static type checkers. This is known as structural subtyping (or static duck-typing):

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

Hơn nữa, bằng cách phân lớp một lớp đặc biệ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])
35, người dùng có thể xác định các giao thức tùy chỉnh mới để thưởng thức hoàn toàn phân nhóm cấu trúc (xem các ví dụ bên dưới).

Nội dung mô -đun

Các mô -đun xác định các lớp, chức năng và trang trí sau đây.

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 có sẵn cũng mở rộ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])
28 để 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:
    ...
49. 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:
    ...
49.

Các loại dự phòng không được chấp nhận kể từ Python 3.9 nhưng không có cảnh báo phản đối nào sẽ được đưa ra bởi thông dịch viên. Dự kiến ​​các 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 sẽ được xóa khỏi 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])
33 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, Generics Generics trong các bộ sưu tập tiêu chuẩn.PEP 585—Type Hinting Generics In Standard Collections.

Đặc biệt gõ nguyên thủy

Các loại đặc biệt

Chúng có thể được sử dụng dưới dạng các loại trong các 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:
    ...
49.

gõ.Any

Loại đặc biệt chỉ ra một loại không bị ràng buộc.

  • Mỗi loại 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])
    
    24.

  • 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 tương thích với mọi loại.

Đã thay đổi trong phiên bản 3.11:

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 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 kiểm tra loại với các lớp có thể loại vịt ở bất cứ đâu hoặc rất nă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])
24 can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

Gõ.LiteralString

Loại đặc biệt chỉ bao gồm các chuỗi theo nghĩa đen. Một chuỗi theo nghĩa đen 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])
54, như 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])
54 khác, nhưng một đối tượng được gõ 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])
31 thì không. Một chuỗi được tạo bằng cách soạn thảo các đối tượng gy ____ 154 cũng được chấp nhận dướ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])
54.

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:
    ...
6

Điều này rất hữu ích cho các API nhạy cảm trong đó các chuỗi do người dùng tạo tùy ý có thể tạo ra vấn đề. Ví dụ, hai trường hợp trên đó tạo ra lỗi kiểm tra loại có thể dễ bị tấn công SQL.

Xem PEP 675 để biết thêm chi tiết.PEP 675 for more details.

Mới trong phiên bản 3.11.

gõ. Không bao giờNever

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,

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:
    ...
61 có thể được sử dụng để thể hiện 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:
    ...
62 đã được thêm vào để làm cho ý định có ý nghĩa rõ ràng hơn.On older Python versions,
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:
    ...
61 may be used to express the same concept.
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:
    ...
62 was added to make the intended meaning more explicit.

Gõ.Noreturn¶NoReturn

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:
    ...
61 cũng có thể được sử dụng như một loại dưới cùng, một loại không có giá trị. Bắt đầu trong Python 3.11, 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:
    ...
62 nên được sử dụng cho khái niệm này. Loại kiểm tra nên đối xử với hai người tương đương.

Mới trong phiên bản 3.5.4.

Mới trong phiên bản 3.6.2.

gõ.SelfSelf

Loạ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 tương đương về mặt ngữ nghĩa với những điều sau đây, mặc dù theo kiểu cô đọng 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 tuân theo mô hình của:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
1

Bạn nên 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])
53 làm cuộc gọi đế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:
    ...
66 sẽ 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:
    ...
67 dưới dạng loại trả về chứ không phả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:
    ...
68.

Các trường hợp sử dụng phổ biến khác bao gồ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:
        ...
    
    69 được sử dụng làm hàm tạo thay thế và các phiên bản trả về của tham số
    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.

  • Chú thích một phương thứ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:
        ...
    
    71 trả về bản thân.

Xem PEP 673 để biết thêm chi tiết.PEP 673 for more details.

Mới trong phiên bản 3.11.

gõ.typealias¶TypeAlias

Chú thích đặc biệt để tuyên bố rõ ràng một bí danh. Ví dụ:type alias. For example:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
2

Xem PEP 613 để biết thêm chi tiết về các bí danh loại rõ ràng.PEP 613 for more details about explicit type aliases.

Mới trong phiên bản 3.10.

Mẫu đặc biệt

Chúng có thể được sử dụng làm loại trong các 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:
    ...
49, mỗi loại có một cú pháp duy nhất.

Gõ.Tuple¶Tuple

Loại tuple;

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:
    ...
73 là loại tuple của hai mục với mục đầu tiên của loại X và loại thứ hai của loại Y. Loại tuple trống có thể được viết 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:
    ...
74.

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:
    ...
75 là một bộ của hai yếu tố tương ứng với các biến loại T1 và 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:
    ...
76 là một bộ dữ liệu của int, float và một chuỗi.

Để chỉ định một tuple có độ dài thay đổi của loại đồng nhất, hãy sử dụng Ellipsis theo nghĩa đen, 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:
    ...
77. Một đơn 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:
    ...
78 tươ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:
    ...
79, và lần lượ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:
    ...
80.

gõ.Union¶Union

Loại công đoà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:
    ...
81 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])
43 và có nghĩa là X hoặc Y.

Để xác định một liên minh, hãy sử dụng, 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:
    ...
83 hoặc tốc ký
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. Sử dụng tốc ký đó được khuyến khích. Thông tin chi tiết:

  • Các đối số phải là loại và phải có ít nhất một.

  • Các công đoàn của các công đoàn bị san phẳng, ví dụ:

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    3

  • Các công đoàn của một cuộc tranh luận duy nhất biến mất, ví dụ:

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    4

  • Các đối số dự phòng được bỏ qua, ví dụ:

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    5

  • Khi so sánh các công đoàn, thứ tự đối số bị bỏ qua, ví dụ:

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    6

  • Bạn không thể phân lớp hoặc khởi tạ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])
    
    25.

  • Bạn không thể viế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:
        ...
    
    86.

Đã thay đổi trong phiên bản 3.7: Don Tiết loại bỏ các lớp con rõ ràng khỏi các công đoàn khi chạy.Don’t remove explicit subclasses from unions at runtime.

gõ.optional¶Optional

Loại tùy chọ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:
    ...
87 tươ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:
    ...
88 (hoặ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:
    ...
89).

Lưu ý rằng đây không phải là khái niệm giống như một đối số tùy chọn, đó là một đối số có mặc định. Một đối số tùy chọn với mặc định không yêu cầu vòng 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:
    ...
90 về chú thích loại của nó chỉ vì nó là tùy chọn. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
7

Mặt khác, nếu giá trị rõ rà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])
58 được phép, việc 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:
    ...
90 là phù hợp, cho dù đối số có phải là tùy chọn hay không. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
8

Đã thay đổi trong phiên bản 3.10: Tùy chọn hiện có thể được viết 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:
    ...
88. Xem biểu thức loại công đoàn.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:
    ...
88. See union type expressions.

Gõ.Callable

Loại có thể gọi đượ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:
    ...
94 là một hàm của (int) -> str.

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à loại trả về. Danh sách đối số phải là danh sách các loại hoặc dấu chấm lửng; Loại trả về phải là một loại duy nhất.

Không có cú pháp để chỉ ra các đối số từ khóa hoặc tùy chọn; Các loại chức năng như vậy hiếm khi được sử dụng làm loại gọi 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])
87 (Ellipsis theo nghĩa đen) có thể được sử dụng để gõ Gợi ý có thể gọi được lấy bất kỳ số lượng đối số nào và trả lạ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:
    ...
96. Một đơ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])
26 tươ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:
    ...
98, và lần lượ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:
    ...
99.

Các thiết bị gọi lấy các thiết bị 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

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])
46. Ngoài ra, nếu có thể gọi được thêm hoặc xóa các đối số khỏi các loại gọi khác, toá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])
47 có thể được sử dụng. Họ lần lượt nhận 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])
90 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])
91.

gõ.concatenate¶Concatenate

Được 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])
26 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])
46 để nhập chú thích một thứ tự cao hơn có thể gọi có thể thêm, xóa hoặc biến đổi các tham số của một người khác có thể gọi được. Việc sử dụng ở dạng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
06.
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])
47 hiện chỉ hợp lệ khi được sử dụng làm đối số đầu tiên cho
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])
26. 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])
47 phả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])
46 hoặc Ellipsis (
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
11).

Ví dụ, để chú thích một người trang trí

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
12 cung cấp một
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
13 cho chức năng được trang trí,
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])
47 có thể được sử dụng để chỉ ra rằng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
12 mong đợi một cuộc gọi có thể gọi được trong một
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
16 là đối số đầu tiên và trả về một dấu hiệu có thể gọi với một loại khác nhau. Trong trường hợp này,
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])
46 chỉ ra rằng các loại tham số có thể gọi được trả về phụ thuộc vào các loại tham số của có thể gọi được được truyền vào:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
9

Mới trong phiên bản 3.10.

Mẫu đặc biệt

  • Chúng có thể được sử dụng làm loại trong các 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:
        ...
    
    49, mỗi loại có một cú pháp duy nhất. – Parameter Specification Variables (the PEP which introduced
    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])
    
    46 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])
    
    47).

  • Gõ.Tuple¶

Loại tuple;
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:
    ...
73 là loại tuple của hai mục với mục đầu tiên của loại X và loại thứ hai của loại Y. Loại tuple trống có thể được viết 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:
    ...
74.
typing.Type(Generic[CT_co])

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:
    ...
75 là một bộ của hai yếu tố tương ứng với các biến loại T1 và 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:
    ...
76 là một bộ dữ liệu của int, float và một chuỗ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)
0

Lưu ý rằng

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
24 là Covariant:

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)
24 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)
22 nên thực hiện cùng một chữ ký của hàm tạo và chữ ký phương pháp lớp là
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
22. Trình kiểm tra loại nên gắn cờ vi phạm này, nhưng cũng nên cho phép các cuộc gọi xây dựng trong các lớp con phù hợp với các cuộc gọi xây dựng trong lớp cơ sở được chỉ định. Làm thế nào 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 sửa đổi trong tương lai của PEP 484.PEP 484.

Các tham số pháp lý duy nhất cho

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
30 là các lớp,
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, các biến loại và liên minh của bất kỳ loại nào trong số này. Ví dụ:type variables, and unions of any of these types. For example:

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)
32 tương đương với
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
30, lần lượt tương đương với
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
34, là gốc của hệ thống phân cấp Metaclass Python.

Mới trong phiên bản 3.5.2.

Gõ.Literal¶Literal

Một loại có thể được sử dụng để chỉ ra các trình kiểm tra loại rằng biến hoặc tham số chức năng tương ứng có giá trị tương đương với nghĩa đen được cung cấp (hoặc một trong một số nghĩa đen). 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)
35 không thể được phân nhóm. Trong thời gian chạy, một giá trị tùy ý được cho phép là đối số loại thành
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
35, nhưng người kiểm tra loại có thể áp đặt các hạn chế. Xem PEP 586 để biết thêm chi tiết về các loại nghĩa đen.PEP 586 for more details about literal types.

Mới trong phiên bản 3.8.

Đã thay đổi trong phiên bản 3.9.1:

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])
38 hiện đã khử trùng các tham số. So sánh bình đẳng của 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])
38 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])
38 hiện sẽ tăng ngoại lệ
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40 trong quá trình so sánh bình đẳng nếu một trong các tham số của chúng không thể băm.
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])
38 now de-duplicates parameters. Equality comparisons 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])
38 objects are no longer order dependent.
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])
38 objects will now raise a
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40 exception during equality comparisons if one of their parameters are not hashable.

Gõ.Classvar¶ClassVar

Loại cấu trúc đặc biệt để đánh dấu các biến lớp.

Như được giới thiệu trong PEP 526, một chú thích thay đổi được bọc trong classvar chỉ ra rằng một thuộc tính nhất định được dự định sẽ được sử dụng làm biến lớp và không nên được đặt trên các trường hợp của lớp đó. Cách sử dụng:PEP 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:

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

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])
34 chỉ chấp nhận các loại và không thể được đăng ký thêm.

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])
34 không phải là một lớp và không nên được sử dụng với
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
43 hoặc
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
44.
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])
34 không thay đổi hành vi thời gian chạy Python, nhưng nó có thể được sử dụng bởi các trình kiểm tra loại bên thứ ba. Ví dụ: Trình kiểm tra loại có thể gắn cờ mã sau 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.

gõ.final¶Final

Một cấu trúc gõ đặc biệt để chỉ ra để nhập trình kiểm tra 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.PEP 591 for more details.

Mới trong phiên bản 3.8.

Đã thay đổi trong phiên bản 3.9.1:
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])
38 hiện đã khử trùng các tham số. So sánh bình đẳng của 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])
38 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])
38 hiện sẽ tăng ngoại lệ
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40 trong quá trình so sánh bình đẳng nếu một trong các tham số của chúng không thể băm.
Requiredtyping.NotRequired

Gõ.Classvar¶

Loại cấu trúc đặc biệt để đánh dấu các biến lớp.PEP 655 for more details.

Như được giới thiệu trong PEP 526, một chú thích thay đổi được bọc trong classvar chỉ ra rằng một thuộc tính nhất định được dự định sẽ được sử dụng làm biến lớp và không nên được đặt trên các trường hợp của lớp đó. 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])
34 chỉ chấp nhận các loại và không thể được đăng ký thêm.
Annotated

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])
34 không phải là một lớp và không nên được sử dụng với
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
43 hoặc
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
44.
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])
34 không thay đổi hành vi thời gian chạy Python, nhưng nó có thể được sử dụng bởi các trình kiểm tra loại bên thứ ba. Ví dụ: Trình kiểm tra loại có thể gắn cờ mã sau là lỗi:PEP 593 (
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
48), to decorate existing types with context-specific metadata (possibly multiple pieces of it, 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])
42 is variadic). Specifically, a 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])
95 can be annotated with metadata
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
51 via the typehint
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
52. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
52 and has no special logic for metadata
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
51, it should ignore it and simply treat the type 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])
95. Unlike the
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
56 functionality that currently exists in 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])
33 module which completely disables typechecking annotations on a function or a class, 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])
42 type allows for both static typechecking 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])
95 (which can safely ignore
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
51) together with runtime access to
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
51 within a specific application.

Mới trong phiên bản 3.5.3.

gõ.final¶

Một cấu trúc gõ đặc biệt để chỉ ra để nhập trình kiểm tra 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ụ:

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.

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

Gõ.Required¶ Gõ.notrequired¶

Các cấu trúc gõ đặc biệt đánh dấu các khóa riêng lẻ 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])
39 theo yêu cầu hoặc không yêu cầu tương ứng.

  • Đối số đầu tiên 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])
    
    42 phải là loại hợp lệ

  • Nhiều chú thích loại được hỗ trợ (

    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])
    
    42 hỗ trợ các đối số variadic):

    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)
    
    8

  • 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])
    
    42 phải được gọi với ít nhất hai đối số (
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    71 không hợp lệ)

  • Thứ tự của các chú thích được bảo tồn và các vấn đề để kiểm tra bình đẳ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)
    
    9

  • Các 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])
    
    42 lồng nhau được làm phẳng, với siêu dữ liệu được đặt hàng bắt đầu với chú thích trong cùng:

    # 'output' is of type 'int', not 'UserId'
    output = UserId(23413) + UserId(54341)
    
    0

  • Chú thích trùng lặp không được xóa:

    # 'output' is of type 'int', not 'UserId'
    output = UserId(23413) + UserId(54341)
    
    1

  • 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])
    
    42 có thể được sử dụng với bí danh lồng nhau và chung chung:

    # 'output' is of type 'int', not 'UserId'
    output = UserId(23413) + UserId(54341)
    
    2

Mới trong phiên bản 3.9.

gõ.typeguard¶TypeGuard

Biểu mẫu gõ đặc biệt được sử dụng để chú thích loại trả về của chức năng bảo vệ loại do người dùng xác đị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])
50 chỉ chấp nhận một đối số loại duy nhất. Trong thời gian chạy, các chức năng được đánh dấu theo cách này sẽ trả về 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])
50 nhằm mục đích thu hẹp loại lợi ích - một kỹ thuật được sử dụng bởi các trình kiểm tra loại tĩnh để xác định một loại biểu thức chính xác hơn trong luồng mã chương trình. Thông thường 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 vào một khối mã. Biểu thức có điều kiện ở đây đôi khi được gọi là một người bảo vệ kiểu người khác:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
3

Đôi khi sẽ thuận tiện khi sử dụng chức năng Boolean do người dùng định nghĩa làm người bảo vệ loại. 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)
76 làm loại trả về của nó để cảnh báo các trình kiểm tra loại tĩnh cho ý định này.

Sử dụng

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
77 nói với trình kiểm tra loại tĩnh rằng đối với một hàm đã cho:

  1. Giá trị trả lại là một boolean.

  2. Nếu giá trị trả về là

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    78, loại đối số của nó là loại bên 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])
    
    50.

Ví dụ:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
4

Nếu

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
80 là phương thức lớp hoặc phiên bản, thì loại 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])
50 bản đồ theo loại 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:
    ...
70 hoặc
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
83.

Nói tóm lại, mẫu ____384, có nghĩa là nếu

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
85 trả về
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
78, thì
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
87 thu hẹp từ
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
88 đến
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
89.

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
89 không cần phải là một dạng hẹp hơn của
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
88 - nó thậm chí có thể là một hình thức rộng hơn. Lý do chính là để cho phép những thứ như thu hẹp
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
92 đến
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
93 mặc dù sau này không phải là một loại phụ của cái trước, vì
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
94 là bất biến. Trách nhiệm của việc viết bộ bảo vệ loại an toàn loại được để lại cho 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])
50 cũng hoạt động với các biến loại. Xem PEP 647 để biết thêm chi tiết.PEP 647 for more details.

Mới trong phiên bản 3.10.

Xây dựng các loại chung chung

Chúng không được sử dụng trong các chú thích. Họ đang xây dựng các khối để tạo ra các loại chung.

classtyping.generic¶typing.Generic

Lớp cơ sở trừu tượng cho các loại chung.

Một loại chung thường được khai báo bằng cách kế thừa từ một khởi tạo của lớp này với một hoặc nhiều biến loại. Ví dụ: loại ánh xạ chung có thể được định nghĩa là:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
5

Lớp này sau đó có thể được sử dụng như sau:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
6

classtyping.typevar¶typing.TypeVar

Loại biến.

Usage:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
7

Loại biến tồn tại chủ yếu vì lợi ích của người kiểm tra loại tĩnh. Chúng phục vụ như các tham số cho các loại chung cũng như các định nghĩa chức năng chung. Xem

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 để biết thêm thông tin về các loại chung. Chức năng chung hoạt động như sau:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
8

Lưu ý rằng các biến loại có thể bị ràng buộc, bị ràng buộc hoặc không, nhưng không thể bị ràng buộc và bị ràng buộc.

Các biến loại ràng buộc và các biến loại bị ràng buộc có ngữ nghĩa khác nhau theo nhiều cách quan trọng. Sử dụng biến loại ràng buộc có nghĩa 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])
27 sẽ được giải quyết bằng cách sử dụng loại cụ thể nhất có thể:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
9

Các biến loại có thể được liên kết với các loại cụ thể, các loại trừu tượng (ABC hoặc giao thức) và thậm chí cả các công đoàn của các loại:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
0

Tuy nhiên, sử dụng một biến loại bị ràng buộc có nghĩa 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])
27 chỉ có thể được giải quyết là chính xác là một trong những ràng buộc được đưa ra:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
1

Trong thời gian chạy,

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
99 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40. Nói chung,
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
43 và
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
44 không nên được sử dụng với các loại.

Các biến loại có thể được đánh dấu hiệp phương sai hoặc contravariant bằng cách vượt qua

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)
03 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. Xem PEP 484 để biết thêm chi tiết. Theo mặc định, các biến loại là bất biến.PEP 484 for more details. By default, type variables are invariant.

classtyping.typevartuple¶typing.TypeVarTuple

Loại biến tuple. Một hình thức chuyên dụng 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)
05 cho phép các chất generic variadic.

Một biến loại bình thường cho phép tham số hóa với một loại duy nhất. Ngược lại, một loại biến loại cho phép tham số hóa với số lượng loại tùy ý bằng cách hoạt động giống như một số lượng biến tùy ý được bọc trong một tuple. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
2

Lưu ý việc sử dụng toán tử giải nén

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 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)
07. Về mặt khái niệm, bạn có thể nghĩ
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 như một bộ biến của các biến loạ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)
09.
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)
07 sau đó sẽ trở 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)
11, tương đương vớ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)
12. .

Loại Tuples biến phải luôn được giải nén. Điều này giúp phân biệt các loại biến loại với các biến loại bình thường:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
3

Loại Tuples biến có thể được sử dụng trong cùng một bối cảnh với các biến loại bình thường. Ví dụ: trong các định nghĩa lớp, đối số và loại trả về:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
4

Loại Tuples biến có thể được kết hợp vui vẻ với các biến loại bình thường:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
5

Tuy nhiên, lưu ý rằng nhiều nhất là một loại biến có thể xuất hiện trong một danh sách các đối số hoặc loại loại loại:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
6

Cuối cùng, một loại biến loại chưa đóng gói có thể được sử dụng làm chú thích loại 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)
15:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
7

Trái ngược với các chú thích không được đóng gói 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)
15 - 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)
17, trong đó sẽ chỉ định rằng tất cả các đối số 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])
61 -
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)
19 cho phép tham chiếu đến các loại đối số riêng lẻ 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)
15. Ở đây, điều này cho phép chúng tôi đảm bảo các loại 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)
15 được chuyển 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)
22 khớp với các loại đối số (vị trí) 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)
23.

Xem PEP 646 để biết thêm chi tiết về các bộ dữ liệu biến loại.PEP 646 for more details on type variable tuples.

Mới trong phiên bản 3.11.

gõ.unpack¶Unpack

Một toán tử đánh máy đánh dấu một đối tượng là đã được giải nén. Ví dụ: sử dụng toán tử unpack

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ên
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 tương đương với việc 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)
13 để đánh dấu loại biến loại loại đã được giải nén:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
8

Trên thực 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)
13 có thể được sử dụng thay thế 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)
06 trong bối cảnh của các loại. Bạn có thể thấ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)
13 đang được sử dụng rõ ràng trong các phiên bản cũ của Python, 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)
06 không thể được sử dụng ở một số nơi nhất định:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
9

Mới trong phiên bản 3.11.

gõ.unpack¶typing.ParamSpec(name, *, bound=None, covariant=False, contravariant=False)

Một toán tử đánh máy đánh dấu một đối tượng là đã được giải nén. Ví dụ: sử dụng toán tử unpack

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ên
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 tương đương với việc 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)
13 để đánh dấu loại biến loại loại đã được giải nén:

Usage:

Trên thực 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)
13 có thể được sử dụng thay thế 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)
06 trong bối cảnh của các loại. Bạn có thể thấ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)
13 đang được sử dụng rõ ràng trong các phiên bản cũ của Python, 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)
06 không thể được sử dụng ở một số nơi nhất định:

classtyping.paramspec (name, *, bound = none, covariant = false

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
0

Biến đặc tả tham số. Một phiên bản chuyên dụng 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)
31.

  1. Các biến đặc tả tham số tồn tại chủ yếu vì lợi ích của bộ kiểm tra loại tĩnh. Chúng được sử dụng để chuyển tiếp các loại tham số của một người có thể gọi cho một người khác có thể gọi - một mẫu thường được tìm thấy trong các chức năng và bộ trang trí bậc cao. Chúng chỉ hợp lệ khi được 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])
    
    47 hoặc là đối số đầu tiên cho
    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])
    
    26 hoặc làm tham số cho thuốc generic do người dùng xác định. Xem
    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 để biết thêm thông tin về các loại chung.

  2. Ví dụ: để thêm ghi nhật ký cơ bản vào một hàm, người ta có thể tạo một trình trang trí

    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 để ghi nhật ký các cuộc gọi chức năng. Biến đặc tả tham số cho biết trình kiểm tra loại rằng có thể gọi được chuyển vào trình trang trí và phần gọi mới được trả về bởi nó có các tham số loại phụ thuộc giữa các tham số:

Không 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])
46, cách đơn giản nhất để chú thích điều này trước đây là 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])
27 với ràng buộ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:
    ...
98. Tuy nhiên, điều này gây ra hai vấn đề:
kwargs

Trình kiểm tra loại có thể loại kiểm tra chức nă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)
39 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)
15 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)
41 phải được gõ
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.

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 có thể được yêu cầu trong phần thân của bộ trang trí
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 khi trả lại hàm
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)
39 hoặc trình kiểm tra loại tĩnh phải được yêu cầu bỏ qua
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)
46.

Args¶ Kwargs¶

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])
46 nắm bắt cả các tham số vị trí và từ khó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)
48 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)
49 có thể được sử dụng để chia
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])
46 thành các thành phần của nó.
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)
48 đại diện cho bộ dữ liệu của các tham số vị trí trong một cuộc gọi nhất định và chỉ nên được sử dụng để chú thí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)
15.
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)
49 đại diện cho ánh xạ các tham số từ khóa đến các giá trị của chúng trong một cuộc gọi nhất định và chỉ nên được sử dụng để chú thí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)
41. Cả hai thuộc tính đều yêu cầu tham số chú thích phải nằm trong phạm vi. Trong thời gian chạ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)
48 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)
49 là các trường hợp tương ứng 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)
57 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)
58.

Các biến đặc tả tham số được tạo bằ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)
03 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 có thể được sử dụng để khai báo các loại chung hiệp phương sai hoặc contravariant. Đối số
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)
61 cũng được chấp nhận, tương tự 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])
27. Tuy nhiên, ngữ nghĩa thực tế của các từ khóa này vẫn chưa được quyết định.

Mới trong phiên bản 3.10.

  • Ghi chú – Parameter Specification Variables (the PEP which introduced

    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])
    
    46 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])
    
    47).

  • Chỉ các biến đặc tả tham số được xác định trong phạm vi toàn cầu mới có thể được ngâm.

Xem thêmParamSpecArgstyping.ParamSpecKwargs

PEP 612 - Các biến đặc tả tham số (PEP đã giới thiệ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])
46 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])
47).

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])
26 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])
47.

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
1

Args¶ Kwargs¶

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])
46 nắm bắt cả các tham số vị trí và từ khó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)
48 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)
49 có thể được sử dụng để chia
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])
46 thành các thành phần của nó.
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)
48 đại diện cho bộ dữ liệu của các tham số vị trí trong một cuộc gọi nhất định và chỉ nên được sử dụng để chú thí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)
15.
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)
49 đại diện cho ánh xạ các tham số từ khóa đến các giá trị của chúng trong một cuộc gọi nhất định và chỉ nên được sử dụng để chú thí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)
41. Cả hai thuộc tính đều yêu cầu tham số chú thích phải nằm trong phạm vi. Trong thời gian chạ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)
48 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)
49 là các trường hợp tương ứng 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)
57 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)
58.
AnyStr

Các biến đặc tả tham số được tạo bằ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)
03 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 có thể được sử dụng để khai báo các loại chung hiệp phương sai hoặc contravariant. Đối số
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)
61 cũng được chấp nhận, tương tự 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])
27. Tuy nhiên, ngữ nghĩa thực tế của các từ khóa này vẫn chưa được quyết định.

Mới trong phiên bản 3.10.

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
2

classtyping.protocol (chung) ¶typing.Protocol(Generic)

Lớp cơ sở cho các lớp giao thức. Các lớp giao thức được xác định như thế này:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
3

Các lớp như vậy chủ yếu được sử dụng với các trình kiểm tra loại tĩnh nhận ra phân nhóm cấu trúc (ví dụ: gõ vịt tĩnh), ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
4

Xem PEP 544 để biết thêm chi tiết. Các lớp giao thức được trang trí vớ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)
78 (được mô tả sau) đóng vai trò là các giao thức thời gian chạy có đầu óc đơn giản chỉ kiểm tra sự hiện diện của các thuộc tính đã cho, bỏ qua các chữ ký loại của chúng.PEP 544 for more details. Protocol classes decorated 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)
78 (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.

Các lớp giao thức có thể là chung chung, ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
5

Mới trong phiên bản 3.8.

@gõ.runtime_checkable¶typing.runtime_checkable

Đánh dấu một lớp giao thức là một giao thức thời gian chạy.

Một giao thức như vậy có thể được sử dụng với

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
43 và
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
44. Điều này tăng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40 khi áp dụng cho một lớp không giao tiếp. Điều này cho phép kiểm tra cấu trúc có đầu óc đơn giản, rất giống với những con ngựa con của One One 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)
82 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:
    ...
43. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
6

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)
78 sẽ chỉ kiểm tra sự hiện diện của các phương pháp cần thiết, không phải chữ ký loại của chúng. 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)
85 là một lớp, do đó nó vượt qua kiểm tra
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
44 đối 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])
26. Tuy nhiên, phương pháp
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)
88 chỉ tồn tại để tăng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40 với một thông điệp nhiều thông tin hơn, do đó khiến nó không thể gọi (khởi tạo)
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)
85.

Mới trong phiên bản 3.8.

@gõ.runtime_checkable¶

Đánh dấu một lớp giao thức là một giao thức thời gian chạy.

Một giao thức như vậy có thể được sử dụng với
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
43 và
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
44. Điều này tăng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40 khi áp dụng cho một lớp không giao tiếp. Điều này cho phép kiểm tra cấu trúc có đầu óc đơn giản, rất giống với những con ngựa con của One One 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)
82 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:
    ...
43. Ví dụ:
typing.NamedTuple

Ghi chú

Usage:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
7

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 sẽ chỉ kiểm tra sự hiện diện của các phương pháp cần thiết, không phải chữ ký loại của chúng. 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)
85 là một lớp, do đó nó vượt qua kiểm tra
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
44 đối 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])
26. Tuy nhiên, phương pháp
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)
88 chỉ tồn tại để tăng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
40 với một thông điệp nhiều thông tin hơn, do đó khiến nó không thể gọi (khởi tạo)
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)
85.

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
8

Các chỉ thị đặc biệt khác

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
9

Chúng không được sử dụng trong các chú thích. Họ đang xây dựng các khối để khai báo các loại.

classtyping.namedtuple¶

Phiên bản gõ 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)
91.

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
0

Điều này tương đương vớ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_update
1

Để cung cấp cho trường một giá trị mặc định, bạn có thể gán cho nó trong phần thân lớp:

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
2

Các trường có giá trị mặc định phải đến sau bất kỳ trường nào mà không có mặc định.Added support for PEP 526 variable annotation syntax.

Lớp kết quả có một thuộc tính bổ sung

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)
92 đưa ra một dictor bản đồ tên trường thành các loại trường. .Added support for default values, methods, and docstrings.

Các lớp con cũng có thể có tài liệu và phương pháp: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)
98 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)
92 attributes are now regular dictionaries instead of instances of
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
00.

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 Các lớp con có thể là chung chung:Removed 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)
98 attribute in favor of the more standard
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)
92 attribute which has the same information.

Sử dụng tương thích ngược:Added support for generic namedtuples.

Đã thay đổi trong phiên bản 3.6: Đã thêm hỗ trợ cho cú pháp chú thích biến PEP 526.typing.NewType(name, tp)

Đã thay đổi trong phiên bản 3.6.1: Đã thêm hỗ trợ cho các giá trị, phương thức và tài liệu mặc định.NewType. At runtime it returns an object that returns its argument when called. Usage:

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
3

Đã thay đổi trong phiên bản 3.8: Các thuộc tí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)
98 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)
92 hiện là từ điển thường xuyên thay vì các trường hợp
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
00.

Đã thay đổi trong phiên bản 3.9: Đã xóa thuộc tí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)
98 có lợi cho thuộc tí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)
92 tiêu chuẩn hơn có cùng thông tin.
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 now a class rather than a function.

Đã thay đổi trong phiên bản 3.11: Đã thêm hỗ trợ cho Generic có tên. typing.TypedDict(dict)

classtyping.newtype (tên, tp) ¶

Một lớp trợ giúp để chỉ ra một loại riêng biệt cho một typechecker, xem newtype. 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_update
4

Mới trong phiên bản 3.5.2.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])
39 supports two additional equivalent syntactic forms:

  • Đã thay đổi trong phiên bản 3.10:

    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 hiện là một lớp chứ không phải là một hàm.

    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
    
    5

  • classtyping.typeddict (dict) ¶

    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
    
    6

Cấu trúc đặc biệt để thêm gợi ý loại vào từ điển. Vào thời gian chạy, nó là một

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
04 đơn giản.The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13. It may also be unsupported by static type checkers.

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])
39 tuyên bố một loại từ điển hy vọng tất cả các trường hợp của nó sẽ có một bộ khóa nhất định, trong đó mỗi khóa được liên kết với giá trị của một loại nhất quán. Kỳ vọng này không được kiểm tra trong thời gian chạy nhưng chỉ được thực thi bởi người kiểm tra loại. Cách sử dụng:identifiers, for example because they are keywords or contain hyphens. Example:

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
7

Để 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])
39 hỗ trợ hai hình thức cú pháp tương đương bổ sung:

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
8

Sử dụng một

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
04 theo nghĩa đen làm đối số thứ hai:

Sử dụng từ khóa đối 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_update
9

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 từ khóa-Progument được không dùng nữa trong 3.11 và sẽ bị xóa trong 3.13. Nó cũng có thể không được hỗ trợ bởi các trình kiểm tra loại tĩnh.

Cú pháp chức năng cũng nên được sử dụng khi bất kỳ khóa nào không phải là định danh hợp lệ, ví dụ vì chúng là từ khóa hoặc chứa dấu gạch nối. Thí dụ:

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
0

Có thể 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])
39 để 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])
39 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: ...
1

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
25 có ba mục:
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
51,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
27 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
28. 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: ...
2

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])
39 không thể kế thừa từ một lớp không phải là -____ 139, ngoại trừ
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. Ví dụ:

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
3

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])
39 có thể là chung:

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])
39 có thể được nội tâm thông qua các chú thích Dicts (xem các chú thích Các thực tiễn tốt nhất để biết thêm thông tin về các chú thích thực hành tốt nhất),
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
34,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
35 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
36.Annotations Best Practices for more information on annotations best practices),
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
34,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
35, and
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
36.

__toàn bộ__¶

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
37 đưa ra giá trị của đối số
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
18. Thí dụ:

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
5

__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)
39 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
40 Trả về
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
41 Các đối tượng có chứa các khóa cần thiết và không yêu cầu, tương ứng.

Các khóa được đánh dấu 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])
51 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
35 và các khóa được đánh dấu 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])
52 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
36.

Đối với khả năng tương thích ngược với Python 3.10 trở xuống, cũng có thể sử dụng kế thừa để khai báo cả các khóa yêu cầu và không yêu cầu 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])
39. Điều này được thực hiện bằng cách khai bá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])
39 với một giá trị cho đối số
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
18 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])
39 khác với giá trị khác cho
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
18:

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
6

Mới trong phiên bản 3.9.

__optional_keys__¶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])
39.

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
39 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
40 Trả về
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
41 Các đối tượng có chứa các khóa cần thiết và không yêu cầu, tương ứng.

Các khóa được đánh dấu 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])
51 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
35 và các khóa được đánh dấu 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])
52 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
36.Added support for marking individual keys 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])
51 or
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. See PEP 655.

Đối với khả năng tương thích ngược với Python 3.10 trở xuống, cũng có thể sử dụng kế thừa để khai báo cả các khóa yêu cầu và không yêu cầu 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])
39. Điều này được thực hiện bằng cách khai bá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])
39 với một giá trị cho đối số
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
18 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])
39 khác với giá trị khác cho
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
18: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])
39s.

Xem PEP 589 để biết thêm ví dụ và quy tắc chi tiết 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]) 39.

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à
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])
51 hoặ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])
52. Xem PEP 655.
typing.Dict(dict, MutableMapping[KT, VT])

Đã thay đổi trong phiên bản 3.11: Đã thêm hỗ trợ cho cá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])
39 chung.

Bộ sưu tập bê tông chung chung

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
7

Tương ứng với các loại tích hợptyping.List(list, MutableSequence[T])

classtyping.dict (dict, mutablemapping [kt, vt]) ¶

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
04. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nó được ưu tiên sử dụng một loại bộ sưu tập trừu tượng như
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
56.

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8

Loại này có thể được sử dụng như sau:typing.Set(set, MutableSet[T])

classtyping.list (Danh sách, Mutablesequence [T]) ¶

Phiên bản chung của
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
94. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nó được ưu tiên sử dụng một loại bộ sưu tập trừu tượng, chẳng hạn như
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
58 hoặ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:
    ...
43.
typing.FrozenSet(frozenset, AbstractSet[T_co])

Loại này có thể được sử dụng như sau:

classtyping.set (set, mutableset [t]) ¶

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
60. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nó được ưu tiên sử dụng một loại bộ sưu tập trừu tượng như
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
61.

classtyping.frozenset (Frozenset, Abstractset [T_CO]) ¶

Một phiên bản chung của
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
62.
typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])

Ghi chú

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 là một hình thức đặc biệt.

Tương ứng với các loại trong ____ 564¶typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])

classtyping.defaultdict (Collections.DefaultDict, Mutablemapping [KT, VT]) ¶

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
65.

Mới trong phiên bản 3.5.2. typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])

classtyping.ordereddict (Collections.ordereddict, mutablemapping [kt, vt]) ¶

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
66.

Mới trong phiên bản 3.7.2.

classtyping.chainmap (bộ sưu tập.chainmap, mutablemapping [kt, vt]) ¶typing.Counter(collections.Counter, Dict[T, int])

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
67.

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
66.

Mới trong phiên bản 3.7.2.

classtyping.chainmap (bộ sưu tập.chainmap, mutablemapping [kt, vt]) ¶ typing.Deque(deque, MutableSequence[T])

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
67.

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
66.

Mới trong phiên bản 3.7.2.

classtyping.chainmap (bộ sưu tập.chainmap, mutablemapping [kt, vt]) ¶

Một phiên bản chung của
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
67.
typing.IOclasstyping.TextIOclasstyping.BinaryIO

Mới trong phiên bản 3.5.4.

Mới trong phiên bản 3.6.1.The

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
74 namespace is deprecated and will be removed. These types should be directly imported from
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 instead.

classtyping.Count (com thu.typing.Patternclasstyping.Match

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
68.

classtyping.deque (deque, mutablesequence [t]) ¶The

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
83 namespace is deprecated and will be removed. These types should be directly imported from
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 instead.

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
69.Classes
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
85 and
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
86 from
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
87 now support
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:
    ...
49. See PEP 585 and Generic Alias Type.

Các loại bê tông kháctyping.Text

classtyping.io¶ classtyping.textio¶ classtyping.binaryio¶

Loại chung

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
70 và các lớp con của nó
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
71 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
72 đại diện cho các loại luồng I/O như được trả về bởi
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
73.

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
9

Mới trong phiên bản 3.5.2.

Không dùng nữa vì 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 loại cũng không còn hỗ trợ kiểm tra loại mã Python 2. Việc loại bỏ bí danh hiện không được lên kế hoạch, nhưng người dùng được khuyến khí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])
31 thay vì
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
89 bất cứ khi nào có thể.Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use
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 instead of
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
89 wherever possible.

Lớp học cơ sở trừu tượng Jo

Tương ứng với các bộ sưu tập trong ____ 482¶

classtyping.abstractset (bộ sưu tập [t_co]) ¶ typing.AbstractSet(Collection[T_co])

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
97.

classtyping.bytestring (trình tự [int]) ¶typing.ByteString(Sequence[int])

Một phiên bản chung của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
98.

Loại này đại diện cho các loại

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
99,
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
00 và
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
01 của các chuỗi byte.

Là một tốc ký cho loại này,

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
99 có thể được sử dụng để chú thích các đối số của bất kỳ loại nào được đề cập ở trên.

classtyping.collection (kích thước, itable [t_co], container [t_co]) ¶ typing.Collection(Sized, Iterable[T_co], Container[T_co])

Phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
03

Mới trong phiên bản 3.6.0.

classtyping.container (chung [t_co]) ¶ typing.Container(Generic[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
04.

classtyping.itemsview (Bản đồView, Tóm tắt [tuple [KT_CO, VT_CO]]) ¶typing.ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
05.

classtyping.keysview (Bản đồView, Abstractset [kt_co]) ¶typing.KeysView(MappingView, AbstractSet[KT_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
06.

classtyping.mapping (bộ sưu tập [kt], chung [kt, vt_co]) ¶ typing.Mapping(Collection[KT], Generic[KT, VT_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
07. Loại này có thể được sử dụng như sau:

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

classtyping.mappingview (kích thước) ¶typing.MappingView(Sized)

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
08.

classtyping.mutablemapping (ánh xạ [kt, vt]) ¶typing.MutableMapping(Mapping[KT, VT])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
09.

classtyping.mutablesequence (trình tự [t]) ¶ typing.MutableSequence(Sequence[T])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
10.

classtyping.mutableset (Tóm tắt [T]) ¶typing.MutableSet(AbstractSet[T])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
11.

classtyping.typing.Sequence(Reversible[T_co], Collection[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
12.

classtyping.valuesview (bản đồ, thu thập [_vt_co]) ¶ typing.ValuesView(MappingView, Collection[_VT_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
13.

Tương ứng với các loại khác trong ____ 482¶

classtyping.iterable (chung [t_co]) ¶typing.Iterable(Generic[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
15.

classtyping.iterator (itable [t_co]) ¶typing.Iterator(Iterable[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
16.

classtyping.generator (iterator [t_co], chung [t_co, t_contra, v_co]) ¶typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])

Một trình tạo có thể được chú thích bằng loại chung

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
17. 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])
01

Lưu ý rằng không giống như nhiều chất generic khác trong mô -đun đánh máy,

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
18 của
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
19 hành xử trái ngược, không bất biến hoặc bất biến.

Nếu trình tạo của bạn chỉ mang lại các 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): pass
18 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:
    ...
96 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])
58:

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

Ngoài ra, chú thích trình tạo của bạn là có loại trả về

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
23 hoặc
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
24:

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

classtyping.hashable¶ typing.Hashable

Một bí danh đến

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
25.

classtyping.Veversible (itable [t_co]) ¶ typing.Reversible(Iterable[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
26.

classtyping.sized¶typing.Sized

Một bí danh đến

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
27.

Lập trình không đồng bộ

classtyping.coroutine (có thể chờ đợi [v_co], chung [t_co, t_contra, v_co]) ¶typing.Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
28. Phương sai và thứ tự của các biến loại tương ứng với các biến của
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
19, 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])
04

Mới trong phiên bản 3.5.3.

classtyping.asyncgenerator (asynciterator [t_co], chung [t_co, t_contra]) ¶typing.AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra])

Một trình tạo async có thể được chú thích bằng loại chung

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
30. 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

Không giống như các trình tạo bình thường, các trình tạo async không thể trả về một giá trị, do đó không có tham số 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:
    ...
96. Như với
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
19,
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
18 hành xử trái ngược nhau.

Nếu trình tạo của bạn chỉ mang lại các 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): pass
18 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])
58:

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

Ngoài ra, chú thích trình tạo của bạn là có loại trả về

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
36 hoặc
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
37:

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

Mới trong phiên bản 3.6.1.

classtyping.asynciterable (chung [t_co]) ¶ typing.AsyncIterable(Generic[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
38.

Mới trong phiên bản 3.5.2.

classtyping.asynciterator (không đồng bộ [T_CO]) ¶typing.AsyncIterator(AsyncIterable[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
39.

Mới trong phiên bản 3.5.2.

classtyping.awaitable (chung [t_co]) ¶ typing.Awaitable(Generic[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
40.

Mới trong phiên bản 3.5.2.

Trình quản lý bối cảnh Loại

classtyping.contextmanager (chung [t_co]) ¶ typing.ContextManager(Generic[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
41.

Mới trong phiên bản 3.5.4.

Mới trong phiên bản 3.6.0.

classtyping.container (chung [t_co]) ¶typing.AsyncContextManager(Generic[T_co])

Một phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
04.

Mới trong phiên bản 3.5.4.

classtyping.asynccontextmanager (chung [t_co]) ¶

Một phiên bản chung của from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not pass type checking class AdminUserId(UserId): pass 42.

Mới trong phiên bản 3.6.2.

Giao thứctyping.SupportsAbs

Các giao thức này được trang trí vớ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)
78.

classtyping.supportsabs¶typing.SupportsBytes

Một ABC với một phương pháp trừu tượng

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
44 là hiệp phương sai trong loại trả lại của nó.

classtyping.supportsbytes¶ typing.SupportsComplex

Một ABC với một phương pháp trừu tượng

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
45.

classtyping.supportscomplex¶ typing.SupportsFloat

Một ABC với một phương pháp trừu tượng

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
46.

classtyping.supportsfloat¶ typing.SupportsIndex

Một ABC với một phương pháp trừu tượng

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
47.

classtyping.supportsindex¶

Một ABC với một phương pháp trừu tượng
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
48.
typing.SupportsInt

Mới trong phiên bản 3.8.

classtyping.supportsInt¶ typing.SupportsRound

Một ABC với một phương pháp trừu tượng

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
49.

Chức năng và Người trang trí

gõ.cast (typ, val) ¶cast(typ, val)

Đúc một giá trị thành một loại.

Điều này trả về giá trị không thay đổi. Đối với người kiểm tra loại 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 cứ điều gì (chúng tôi muốn điều này càng nhanh càng tốt).

gõ.assert_type (val, typ, /) ¶assert_type(val, typ, /)

Hỏi một trình kiểm tra loại tĩnh để xác nhận rằng Val có một loại type được suy ra.

Khi trình kiểm tra loại gặp phải cuộc gọi đến

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
51, nó sẽ phát ra lỗi nếu giá trị không thuộc loại được 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])
08

Vào thời gian 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 rất hữu ích để đảm bảo loại kiểm tra loại hiểu về một 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])
09

Mới trong phiên bản 3.11.

gõ.assert_never (arg, /) ¶assert_never(arg, /)

Hỏi trình kiểm tra loại tĩnh để xác nhận rằng một dòng mã là không thể truy cập được.

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])
10

Ở đây, các chú thích cho phép trình kiểm tra loại suy ra rằng trường hợp cuối cùng không bao giờ có thể thực thi, bởi vì

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
87 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])
61 hoặ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])
31 và cả hai tùy chọn đều được bao gồm bởi các trường hợp trước đó. Nếu một trình kiểm tra loại thấy rằng một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
55 có thể truy cập được, nó sẽ phát ra một lỗi. Ví dụ: nếu chú thích loại cho
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
87 thay vào đó là
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
57, trình kiểm tra loại sẽ phát ra một lỗi chỉ ra rằng
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
58 là loại
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
59. Đối với một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
60 để vượt qua kiểm tra loại, loại được suy ra của đối số được truyền trong phải là loại dưới cù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:
    ...
62 và không có gì khác.

Trong thời gian chạy, điều này ném một ngoại lệ khi được gọi.

Mới trong phiên bản 3.11.

gõ.assert_never (arg, /) ¶reveal_type(obj, /)

Hỏi trình kiểm tra loại tĩnh để xác nhận rằng một dòng mã là không thể truy cập được.

Ở đây, các chú thích cho phép trình kiểm tra loại suy ra rằng trường hợp cuối cùng không bao giờ có thể thực thi, bởi vì

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
87 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])
61 hoặ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])
31 và cả hai tùy chọn đều được bao gồm bởi các trường hợp trước đó. Nếu một trình kiểm tra loại thấy rằng một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
55 có thể truy cập được, nó sẽ phát ra một lỗi. Ví dụ: nếu chú thích loại cho
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
87 thay vào đó là
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
57, trình kiểm tra loại sẽ phát ra một lỗi chỉ ra rằng
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
58 là loại
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
59. Đối với một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
60 để vượt qua kiểm tra loại, loại được suy ra của đối số được truyền trong phải là loại dưới cù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:
    ...
62 và không có gì khá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])
11

Trong thời gian chạy, điều này ném một ngoại lệ khi được gọi.

gõ.reveal_type (obj, /) ¶

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

Tiết lộ loại tĩnh suy ra của một biểu thức.

Khi trình kiểm tra loại tĩnh bắt gặp một cuộc gọi đến chức năng này, nó sẽ phát ra một chẩn đoán với loại đố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])
13

Mới trong phiên bản 3.11.

gõ.assert_never (arg, /) ¶typing.dataclass_transform

Hỏi trình kiểm tra loại tĩnh để xác nhận rằng một dòng mã là không thể truy cập được.

Ở đây, các chú thích cho phép trình kiểm tra loại suy ra rằng trường hợp cuối cùng không bao giờ có thể thực thi, bởi vì

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
87 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])
61 hoặ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])
31 và cả hai tùy chọn đều được bao gồm bởi các trường hợp trước đó. Nếu một trình kiểm tra loại thấy rằng một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
55 có thể truy cập được, nó sẽ phát ra một lỗi. Ví dụ: nếu chú thích loại cho
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
87 thay vào đó là
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
57, trình kiểm tra loại sẽ phát ra một lỗi chỉ ra rằng
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
58 là loại
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
59. Đối với một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
60 để vượt qua kiểm tra loại, loại được suy ra của đối số được truyền trong phải là loại dưới cù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:
    ...
62 và không có gì khá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])
14

Trong thời gian chạy, điều này ném một ngoại lệ khi được 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])
15

gõ.reveal_type (obj, /) ¶

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

Tiết lộ loại tĩnh suy ra của một biểu thức.

Khi trình kiểm tra loại tĩnh bắt gặp một cuộc gọi đến chức năng này, nó sẽ phát ra một chẩn đoán với loại đối số. Ví dụ:

Điều này có thể hữu ích khi bạn muốn gỡ lỗi cách người 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:

  • Hầu hết các trình kiểm tra loại hỗ trợ

    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    62 ở bất cứ đâu, 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])
    
    33. 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])
    
    33 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.

  • Khi chạy, chức năng này in loại thời gian chạy của đối số của nó thành stderr và trả về nó không thay đổi:

  • @Gõ.DataClass_Transform¶

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    65 có thể được sử dụng để trang trí một lớp, metaclass hoặc một chức năng tự nó là một người trang trí. Sự hiện diện của
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    66 cho biết một trình kiểm tra loại tĩnh rằng đối tượng được trang trí thực hiện thời gian chạy ma thuật, biến đổi một lớp, đưa ra các hành vi giống như ____ 667.

Ví dụ sử dụng với chức năng trang trí:

  • Trên một lớp cơ sở:

  • Trên một metaclass:

  • Các lớp

    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    68 được xác định ở trên sẽ được xử lý bởi các trình kiểm tra loại tương tự như các lớp được tạo bằng
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    69. Ví dụ: trình kiểm tra loại sẽ giả sử các lớp này có các phương thức
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    70 chấp nhận
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    71 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])
    
    30.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    03 là bí danh cho
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    00.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    80 cho biết trường có nên được đánh dấu là chỉ từ khóa hay không. Nếu
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    78, trường sẽ chỉ dành cho từ khóa. Nếu
    # 'output' is of type 'int', not 'UserId'
    output = UserId(23413) + UserId(54341)
    
    13, nó sẽ không chỉ là từ khóa. Nếu không xác định, giá trị của tham số
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    80 trên đối tượng được trang trí bằng
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    65 sẽ được sử dụng hoặc nếu điều đó không được xác định, giá trị của
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    91 trên
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    65 sẽ được sử dụng.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    12 cung cấp một tên thay thế cho trường. Tên thay thế này được sử dụng trong phương pháp
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    70 tổng hợp.

Trong thời gian chạy, người trang trí này ghi lại các lập luận của nó trong thuộc tính

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
14 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.PEP 681 for more details.

Mới trong phiên bản 3.11.

@Gõ.Overload¶typing.overload

Trình trang trí

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
15 cho phép mô tả các chức năng và phương pháp 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í ____ 715 phải được theo sau bởi chính xác một định nghĩa không được trang trí 715 (cho cùng một hàm/phương thức). Các định nghĩa được trang trí ____ 715 chỉ vì 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í 715, trong khi loại sau được sử dụng trong thời gian chạy nhưng nên bị bỏ qua bởi trình kiểm tra loại. Trong thời gian chạy, gọi trực tiếp chức năng được trang trí ____ 715 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
21. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được thể hiện bằng cách sử dụng một 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])
17

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.PEP 484 for more details and comparison with other typing semantics.

Đã thay đổi trong phiên bản 3.11: Các chức năng quá tải hiện có thể được nội tâm khi chạy bằng cách sử dụng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
22.Overloaded functions can now be introspected at runtime using
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
22.

gõ.get_overloads (func) ¶get_overloads(func)

Trả về một chuỗi các định nghĩa được trang trí ____ 715 cho FUNC. Func là đối tượng chức năng để thực hiện chức năng quá tải. Ví dụ: với định nghĩa của

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
24 trong tài liệu cho
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
15,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
26 sẽ trả về một chuỗi ba đối tượng chức năng cho ba quá tải được xác định. Nếu được gọi trên một hàm không có quá tải,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
22 sẽ trả về một chuỗi trống.

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
22 có thể được sử dụng để hướng nội một chức năng quá tải trong thời gian chạy.

Mới trong phiên bản 3.11.

@Gõ.Overload¶clear_overloads()

Trình trang trí

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
15 cho phép mô tả các chức năng và phương pháp 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í ____ 715 phải được theo sau bởi chính xác một định nghĩa không được trang trí 715 (cho cùng một hàm/phương thức). Các định nghĩa được trang trí ____ 715 chỉ vì 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í 715, trong khi loại sau được sử dụng trong thời gian chạy nhưng nên bị bỏ qua bởi trình kiểm tra loại. Trong thời gian chạy, gọi trực tiếp chức năng được trang trí ____ 715 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
21. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được thể hiện bằng cách sử dụng một liên kết hoặc biến loại:

Mới trong phiên bản 3.11.

@Gõ.Overload¶typing.final

Trình trang trí

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
15 cho phép mô tả các chức năng và phương pháp 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í ____ 715 phải được theo sau bởi chính xác một định nghĩa không được trang trí 715 (cho cùng một hàm/phương thức). Các định nghĩa được trang trí ____ 715 chỉ vì 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í 715, trong khi loại sau được sử dụng trong thời gian chạy nhưng nên bị bỏ qua bởi trình kiểm tra loại. Trong thời gian chạy, gọi trực tiếp chức năng được trang trí ____ 715 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
21. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được thể hiện bằng cách sử dụng một 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.PEP 591 for more details.

Đã thay đổi trong phiên bản 3.11: Các chức năng quá tải hiện có thể được nội tâm khi chạy bằng cách sử dụng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
22.

gõ.get_overloads (func) ¶The decorator will now set the

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
29 attribute to
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
78 on the decorated object. Thus, a check like
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
31 can be used at runtime to determine whether an object
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
32 has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

Trả về một chuỗi các định nghĩa được trang trí ____ 715 cho FUNC. Func là đối tượng chức năng để thực hiện chức năng quá tải. Ví dụ: với định nghĩa của
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
24 trong tài liệu cho
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
15,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
26 sẽ trả về một chuỗi ba đối tượng chức năng cho ba quá tải được xác định. Nếu được gọi trên một hàm không có quá tải,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
22 sẽ trả về một chuỗi trống.
typing.no_type_check

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
22 có thể được sử dụng để hướng nội một chức năng quá tải trong thời gian chạy.

gõ.clear_overloads () ¶decorator. With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses).

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 để đòi lại bộ nhớ được sử dụng bởi sổ đăng ký.

@Gõ.Final¶typing.no_type_check_decorator

Một người trang trí để chỉ ra để gõ các trình kiểm tra rằng phương pháp được trang trí không thể được ghi đè, và lớp được trang trí không thể được phân nhóm. Ví dụ:

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.typing.type_check_only

Đã thay đổi trong phiên bản 3.11: Trình trang trí hiện sẽ đặt thuộc tính

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
29 thành
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
78 trên đối tượng được trang trí. Do đó, một kiểm tra như
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
31 có thể được sử dụng trong thời gian chạy để xác định xem một đối tượng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
32 có được đánh dấu là cuối cùng hay không. Nếu đối tượng được trang trí không hỗ trợ các thuộc tính thiết lập, người trang trí trả về đối tượng không thay đổi mà không gây ra ngoại lệ.

@gõ.no_type_check¶

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

Trang trí để chỉ ra rằng chú thích không phải là gợi ý loại.

Điều này hoạt động như là người trang trí đẳng cấ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 xác định trong lớp đó (nhưng không phải là các phương thức được xác định trong các lớp học hoặc các lớp con).

Điều này làm thay đổi (các) hàm tại chỗ.get_type_hints(obj, globalns=None, localns=None, include_extras=False)

@gõ.no_type_check_decorator¶

Người trang trí để cung cấp cho một người trang trí khác hiệu ứng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
33.

Điều này kết thúc công cụ trang trí bằng một cái gì đó kết thúc chức năng được trang trí trong

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
33.

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

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
67 không hoạt động với các bí danh loại nhập khẩu bao gồm các tài liệu tham khảo phía trước. Cho phép đánh giá các chú thích (PEP 563) có thể loại bỏ nhu cầu về hầu hết các tài liệu tham khảo chuyển tiếp.type aliases that include forward references. Enabling postponed evaluation of annotations (PEP 563) may remove the need for most forward references.

Đã thay đổi trong phiên bản 3.9: Đã thêm tham số

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
43 như là một phần của PEP 593.Added
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
43 parameter as part of PEP 593.

Đã thay đổi trong phiên bản 3.11: Trước đây,

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
48 đã được thêm vào cho các chú thích chức năng 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])
58 được đặt. Bây giờ chú thích được trả lại không thay đổi.Previously,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
48 was added for function and method annotations if a default value equal 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])
58 was set. Now the annotation is returned unchanged.

gõ.get_args (tp) ¶ gõ.get_origin (tp) ¶get_args(tp)typing.get_origin(tp)

Cung cấp nội tâm 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 typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
50, các chức năng này trả về
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
51 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
52. Nếu
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
51 là bí danh chung cho lớp tích hợp hoặc
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
64, thì nó sẽ được chuẩn hóa thành lớp ban đầu. Nếu
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
51 là một liên minh hoặ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])
38 có trong một loại chung khác, thì thứ tự của
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
52 có thể khác với thứ tự của các đối số gốc
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
58 do bộ nhớ đệm loại. Đối với các đối tượng không được hỗ trợ trả 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])
58 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
60 tương ứng. 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

Mới trong phiên bản 3.8.

gõ.is_typeddict (tp) ¶is_typeddict(tp)

Kiểm tra xem một loạ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])
39.

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.10.

classtyping.forwardref¶typing.ForwardRef

Một lớp được sử dụng để biểu diễn gõ nội bộ của các tham chiếu chuyển tiếp chuỗi. Ví dụ,

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
62 được chuyển đổi hoàn toàn thành
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
63. Lớp này không nên được người dùng khởi tạo, nhưng có thể được sử dụng bởi các công cụ hướng nội.

Ghi chú

PEP 585 Các loại chung như

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
64 sẽ không được chuyển đổi hoàn toàn thành
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
65 và do đó sẽ không tự động giải quyết thành
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
66.
generic types such as
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
64 will not be implicitly transformed into
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
65 and thus will not automatically resolve to
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
66.

Mới trong phiên bản 3.7.4.

Không thay đổi¶

gõ.type_checking¶TYPE_CHECKING

Một hằng số đặc biệt được giả định là

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
78 bởi người 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)
13 khi 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])
23

Chú thích loại đầu tiên phải được đặt trong các trích dẫn, làm cho nó trở thành một tài liệu tham khảo phía trước, để ẩn tham chiếu

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
69 từ thời gian chạy của 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 các trích dẫn.

Ghi chú

Nếu

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
70 được sử dụng, các chú thích không được đánh giá theo thời gian định nghĩa chức năng. Thay vào đó, chúng được lưu trữ dưới dạng chuỗi 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)
92. Điều này làm cho việc sử dụng các trích dẫn xung quanh chú thích không cần thiết (xem PEP 563).PEP 563).

Mới trong phiên bản 3.5.2.

Dòng thời gian phản đối của các tính năng chính

Một số tính năng nhất định 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])
33 được không dùng nữa và có thể bị xóa trong phiên bản Python trong tương lai. Bảng sau đây tóm tắt các khấu hao lớn cho sự thuận tiện của bạn. Điều này có thể thay đổi, và không phải tất cả các giá khấu được liệt kê.

Tính năng

Phản đối trong

Loại bỏ dự kiến

PEP/issue

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
74 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
83

3.8

3.13

bpo-38291

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 phiên bản của các bộ sưu tập tiêu chuẩn

3.9

Chưa quyết định

PEP 585

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
76

3.11

Chưa quyết định

gh-92332