Hướng dẫn do you need to specify type in python? - bạn có cần chỉ định loại trong python không?

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

from collections.abc import Mapping, Sequence

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

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

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
00,
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
01 và
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02. Để 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
03, đối số
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
04 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
05 và loại trả về
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
05. 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
07. 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.

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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    08

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    09 và người trang trí
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    10

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    11 và khả năng sử dụng các lớp thư viện tiêu chuẩn làm loại chung 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    12

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    13

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    14 và người trang trí
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    15

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    16

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    17
    : Allow writing union types as
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    17

    Giới thiệu

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    18 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    19 để 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    20 và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    21

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    22

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    23

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]

# typechecks; 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
25 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]

# typechecks; 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27.

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 để tạo các loại khác biệt:

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
29 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
30, 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
29. Đ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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
30 bất cứ nơi nào có thể mong đợi
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
29, 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
30 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
35 sẽ biến
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
37 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
38 luôn đúng khi chạy.

Thật 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 dựa trên một ____ ____ ____128:

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
43 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
44 là chính xác tương đương với
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
45 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
47 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
45, 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
45 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36. Đ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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 qua 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
54.

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
55.

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20. 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
21 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
58 và
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
59.

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
01.

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; 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]

# typechecks; 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
61 dưới dạng 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
62 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63. Đ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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 xác định
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
66 để
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
67 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]

# typechecks; 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 loại của

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
01 đều được cho phép làm tham số cho loại chung:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 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]

# typechecks; 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; 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]

# typechecks; 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

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
71 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63.

Sử dụng một lớp chung mà không chỉ định các tham số loại giả định

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 cho mỗi vị trí. Trong ví dụ sau,
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
74 không chung chung mà là kế thừa ngầm từ
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
75:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; 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]

# typechecks; 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 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

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
77. 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; 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

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
79 và cả
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
80 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 có thể không đúng
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
82 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 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 from collections.abc import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: ... 8

Một loại đặc biệt là

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8. Một trình kiểm tra loại tĩnh sẽ coi mọi loại là tương thích với
from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 và
from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 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

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 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ó typechking nào được thực hiện khi gán giá trị loại

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 cho một 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
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
91 cho
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
92 mặc dù
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
92 đã được tuyên bố là loại
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
05 và nhận được giá trị
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
29 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 sử dụng

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[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:
    ...
2

Hành vi này cho phép

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 đượ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

from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 với hành vi của
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
99. Tương tự như
from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8, mọi loại là một loại phụ của
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
99. Tuy nhiên, không giống như
from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8, điều ngược lại không đúng:
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
99 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à

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
99, 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

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
99 để 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
from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8 để 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:
    ...
07 đượ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:
    ...
08 đượ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:
    ...
07 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:
    ...
08.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:
    ...
07 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:
    ...
08 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:
    ...
07 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:
    ...
08.

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:
    ...
11. 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:
    ...
12 được coi là một kiểu con của cả hai 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:
    ...
12 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:
    ...
13 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:
    ...
14 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
09, 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 để 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:
    ...
17. 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:
    ...
17.

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
07 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 làm 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:
    ...
17.

________ 221 ________ 222¶

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

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

  • from collections.abc import Mapping, Sequence
    
    def notify_by_email(employees: Sequence[Employee],
                        overrides: Mapping[str, str]) -> None: ...
    
    8 tương thích với mọi loại.

________ 221 ________ 226¶

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

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

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

________ 221 ________ 228¶

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

from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
7

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:
    ...
17, mỗi loại có một cú pháp duy nhất.

________ 221 ________ 231¶

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:
    ...
32 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:
    ...
33.

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:
    ...
34 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:
    ...
35 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:
    ...
36. 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:
    ...
37 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:
    ...
38, 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:
    ...
39.

________ 221 ________ 241¶

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:
    ...
42 tương đương với
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
17 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:
    ...
44 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:
    ...
45. 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 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

  • 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 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

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

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

  • 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)
    
    1

  • Bạn không thể phân lớp hoặc khởi tạo

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

  • 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:
        ...
    
    47.

Đã 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.

________ 221 ________ 249¶

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:
    ...
50 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:
    ...
51 (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:
    ...
52).

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:
    ...
53 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)
2

Mặt khác, nếu được phép một giá trị rõ ràng của

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26, 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:
    ...
53 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)
3

Đã 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:
    ...
51. 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:
    ...
51. See union type expressions.

________ 221 ________ 258¶

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:
    ...
59 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
55 (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:
    ...
61. Một đơn vị
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
00 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:
    ...
63, 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:
    ...
64.

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20. 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
21 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
58 và
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
59.

________ 221 ________ 270¶

Được sử dụng với

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
00 và
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 để 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 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.
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
21 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
00. Tham số cuối cùng đến
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
21 phải là
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20.

Ví dụ, để chú thích một người trang 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:
    ...
78 cung cấp 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:
    ...
79 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
21 có thể được sử dụng để chỉ ra rằ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:
    ...
78 mong đợi một cuộc gọi có thể gọi được trong 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:
    ...
82 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 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)
4

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

Xem thêm

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    20 và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    21).
    – Parameter Specification Variables (the PEP which introduced
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    20 and
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    21).

  • Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    20 và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    00.

Lớp ________ 221 ________ 289 (chung [CT_CO]) ¶(Generic[CT_co])

Một biến được chú thích bằng

from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
90 có thể chấp nhận giá trị 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. Ngược lại, một biến được chú thích bằng
from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
92 có thể chấp nhận các giá trị là bản thân các lớp - cụ thể, nó sẽ chấp nhận đối tượng lớp 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:
    ...
90. Ví dụ:

from typing import NewType

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

Lưu ý rằ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:
    ...
92 là Covariant:

from typing import NewType

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

Thực 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:
    ...
92 là hiệp phương sai ngụ ý rằng tất cả các 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:
    ...
90 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 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. 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 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 là các lớp,
from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
8, các biến loại và các công đoàn 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:

from typing import NewType

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
00 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, lần lượt tương đương với
from typing import NewType

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

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

________ 221 ________ 304¶

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ụ:

from typing import NewType

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
05 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)
05, 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 hiện sẽ tăng ngoại lệ
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
10 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 now de-duplicates parameters. Equality comparisons of
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 objects are no longer order dependent.
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 objects will now raise a
from typing import NewType

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

________ 221 ________ 312¶

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:

from typing import NewType

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

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
08 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
08 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)
15 hoặc
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
16.
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
08 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
0

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

________ 221 ________ 319¶

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
1

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.

________ 221 ________ 321¶

Một loại, được giới thiệu trong PEP 593 (

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
22), để trang trí các loại hiện có với siêu dữ liệu cụ thể theo ngữ cảnh (có thể là nhiều phần của nó, vì
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16 là variadic). Cụ thể, loại
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 có thể được chú thích bằng siêu dữ liệu
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
25 thông qua TypeHint
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
26. Siêu dữ liệu này có thể được sử dụng để phân tích tĩnh hoặc trong thời gian chạy. Nếu một thư viện (hoặc công cụ) gặp phải một kiểu chữ
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
26 và không có logic đặc biệt cho siêu dữ liệu
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
25, nó sẽ bỏ qua nó và chỉ coi loại này là
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63. Không giống như chức năng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
30 hiện đang tồn tại trong mô -đun ____107, vô hiệu hóa hoàn toàn các chú thích đánh máy trên một hàm hoặc một lớp, loại
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16 cho phép cả hai lần kiểm tra typic của
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 (có thể bỏ qua một cách an toàn .PEP 593 (
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
22), 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16 is variadic). Specifically, a type
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 can be annotated with metadata
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
26. 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)
26 and has no special logic for metadata
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
25, 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63. Unlike the
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
30 functionality that currently exists in the
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
07 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16 type allows for both static typechecking of
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 (which can safely ignore
from typing import NewType

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

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

Cuối cùng, trách nhiệm của cách diễn giải các chú thích (nếu có) là trách nhiệm của công cụ hoặc thư viện gặp phải loại

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16. Một công cụ hoặc thư viện gặp phải loại
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16 có thể quét qua các chú thích để xác định xem chúng có được quan tâm không (ví dụ: sử dụng
from typing import NewType

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

Khi một công cụ hoặc thư viện không hỗ trợ chú thích hoặc gặp một chú thích không xác định, nó chỉ nên bỏ qua nó và coi loại chú thích là loại cơ bản.

Nó tùy thuộc vào công cụ tiêu thụ các chú thích để quyết định xem khách hàng có được phép có nhiều chú thích trên một loại hay không và làm thế nào để hợp nhất các chú thích đó.

Vì loại

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16 cho phép bạn đặt một số chú thích cùng loại (hoặc khác nhau) trên bất kỳ nút nào, nên các công cụ hoặc thư viện tiêu thụ các chú thích đó chịu trách nhiệm đối phó với các bản sao tiềm năng. Ví dụ: nếu bạn đang thực hiện phân tích phạm vi giá trị, bạn có thể cho phép điều này:

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
2

Chuyển

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
41 cho phép người ta truy cập vào các chú thích bổ sung khi chạy.

Các chi tiết của cú pháp:

  • Đối số đầu tiên cho

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    16 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    16 hỗ trợ các đối số variadic):

    def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    3

  • Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    16 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)
    
    45 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:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    4

  • Các loại

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    16 đượ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:

    def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    5

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

    def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    6

  • Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    16 có thể được sử dụng với bí danh lồng nhau và chung chung:

    def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    7

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

________ 221 ________ 349¶

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
23 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
23 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:

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
8

Đô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)
52 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)
53 cho biết 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)
    
    54, 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    23.

Ví dụ:

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
9

Nếu

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
56 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
23 bản đồ theo loại tham số thứ hai sau
from typing import NewType

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

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

Nói tóm lại, mẫu

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
60, có nghĩa là nếu
from typing import NewType

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

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

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

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

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

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
65 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)
64 - 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)
68 đến
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
69 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)
70 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
23 cũng hoạt động với các biến loại. Để biết thêm thông tin, hãy xem PEP 647 (Bộ bảo vệ loại do người dùng xác định).PEP 647 (User-Defined Type Guards).

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.

Lớp ________ 221 ________ 373¶

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

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

Lớp ________ 221 ________ 375¶

Loại biến.

Usage:

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

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 để 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)
3

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 bị ràng buộc và các biến loại ràng buộc có ngữ nghĩa khác nhau theo một số cách quan trọng. 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
01 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:

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

Tuy nhiên, sử dụng một 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
01 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)
5

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:

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

Các biến loại ràng buộc đặc biệt hữu ích để chú thích

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
79 đóng vai trò là hàm tạo thay thế. Trong ví dụ sau (bởi Raymond Hettinger), biến 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 được liên kết với lớp
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
81 thông qua việc sử dụng tham chiếu chuyển tiếp. Sử dụng biến loại này để chú thích lớp
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
82, thay vì mã hóa loại trả về loại trả về
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
81, có nghĩa là trình kiểm tra loại có thể suy ra chính xác loại trả về ngay cả khi phương thức được gọi trên lớp con:

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

Trong thời gian chạy,

from typing import NewType

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

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

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
16 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

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
89. 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.

Lớp ________ 221 ________ 391 (Tên, *, Bound = none, Covariant = false(name, *, bound=None, covariant=False, contravariant=False)

Biến đặc tả tham số. Một phiên bản chuyên dụng của

from typing import NewType

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

Usage:

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
21 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
00 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
02 để biết thêm thông tin về các loại chung.

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
96 để 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ố:

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

Không có

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20, 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
01 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:
    ...
63. Tuy nhiên, điều này gây ra hai vấn đề:

  1. 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:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    00 vì
    def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    01 và
    def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    02 phải được gõ
    from collections.abc import Mapping, Sequence
    
    def notify_by_email(employees: Sequence[Employee],
                        overrides: Mapping[str, str]) -> None: ...
    
    8.

  2. def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    04 có thể được yêu cầu trong thân máy trang trí
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    96 khi trả lại hàm
    def get_user_name(user_id: UserId) -> str:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    00 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:
        ...
    
    # typechecks
    user_a = get_user_name(UserId(42351))
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name(-1)
    
    07.

________ 408¶ ________ 409¶

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 nắm bắt cả các tham số vị trí và từ khóa,
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
11 và
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
12 có thể được sử dụng để chia
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 thành các thành phần của nó.
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
11 đạ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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
01.
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
12 thể hiện á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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
02. 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
11 và
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
12 tương ứng là các trường hợp của
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
20 và
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
21.

Các biến đặc tả tham số được tạo bằng

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
89 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
24 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
01. 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ú

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êm

  • 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]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    20 và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    21).
    – Parameter Specification Variables (the PEP which introduced
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    20 and
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    21).

  • Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    00 và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    21.

________ 221 ________ 431¶ ________ 221 ________ 433¶

Đối số và từ khóa Các thuộc tính của A

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20. Thuộc tính
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
11 của
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 là một ví dụ là
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
20 và
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
12 là một ví dụ của
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
21. Chúng được dự định để hướng nội thời gian chạy và không có ý nghĩa đặc biệt đối với người kiểm tra loại tĩnh.

Gọi

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
40 trên một trong hai đối tượng này sẽ trả về
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 gốc:

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

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

________ 221 ________ 443¶

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
44 là
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
45 được định nghĩa là
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
46.

Nó có nghĩa là được sử dụng cho các chức năng có thể chấp nhận bất kỳ loại chuỗi nào mà không cho phép các loại chuỗi khác nhau trộn. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

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

Lớp ________ 221 ________ 448 (chung) ¶(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)

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

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)

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

Xem PEP 544 để biết chi tiết. Các lớp giao thức được trang trí với

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
49 (đượ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 details. Protocol classes decorated with
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
49 (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)

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

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

________ 450 ________ 221 ________ 452¶

Đá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)
15 và
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
10 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
56, 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:
    ...
11. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

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

Ghi chú

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
49 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
59 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)
16 đối với
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
00. Tuy nhiên, phương pháp
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
62 chỉ tồn tại để tăng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
10 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
59.

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

________ 450 ________ 221 ________ 452¶

Đá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)
15 và
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
10 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
56, 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:
    ...
11. Ví dụ:

Ghi chú

Usage:

from typing import NewType

UserId = NewType('UserId', int)

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

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
49 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
59 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)
16 đối với
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
00. Tuy nhiên, phương pháp
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
62 chỉ tồn tại để tăng
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
10 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:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
59.

from typing import NewType

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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.

Lớp ________ 221 ________ 466¶

Phiên bản gõ của

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
67.

from typing import NewType

UserId = NewType('UserId', int)

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

Điều này tương đương với:

from typing import NewType

UserId = NewType('UserId', int)

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

Để 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:Added support for PEP 526 variable annotation syntax.

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 default values, methods, and docstrings.

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

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
68 đưa ra một dictor bản đồ tên trường thành các loại trường. .The
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
73 and
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
68 attributes are now regular dictionaries instead of instances of
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
75.

Các lớp con cũng có thể có tài liệu và phương pháp:Removed the

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
73 attribute in favor of the more standard
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
68 attribute which has the same information.

Sử dụng tương thích ngược:(name, tp)

Đã thay đổi trong phiên bản 3.6: Đã thêm hỗ trợ cho cú pháp chú thích biến PEP 526.NewType. At runtime it returns an object that returns its argument when called. Usage:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
0

Đã 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.

Đã thay đổi trong phiên bản 3.8: Các thuộc tính

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
73 và
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
68 hiện là từ điển thường xuyên thay vì các trường hợp
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
75.
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 is now a class rather than a function.

Đã thay đổi trong phiên bản 3.9: Đã xóa thuộc tính
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
73 có lợi cho thuộc tính
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
68 tiêu chuẩn hơn có cùng thông tin.(dict)

Lớp ________ 221 ________ 479 (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 typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
1

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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 supports two additional equivalent syntactic forms:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
28 hiện là một lớp chứ không phải là một hàm.identifiers, for example because they are keywords or contain hyphens. Example:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
3

Lớp ________ 221 ________ 482 (Diễn ngôn) ¶

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
4

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

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
83 đơn giản.

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 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:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
5

Để 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 hỗ trợ hai hình thức cú pháp tương đương bổ sung:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
6

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 typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
7

A

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 có thể được nội tâm thông qua các chú thích Dicts (xem các thông chứng thực hành tốt nhất để biết thêm thông tin về các thông lệ thực hành tốt nhất),
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
03,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
04 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
05.Annotations Best Practices for more information on annotations best practices),
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
03,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
04, and
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
05.

________ 506¶

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
07 đưa ra giá trị của đối số
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
91. Thí dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
8

________ 509¶

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

________ 510¶

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
11 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
12 Trả về
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
13 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. Hiện tại, cách duy nhất để 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 là kế thừa hỗn hợp, khai báo
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 với một giá trị cho đối số
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
91 và sau đó kế thừa nó từ một
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 khác với giá trị khác với
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
91. Cách sử dụng:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
9

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

________ 510¶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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13.

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
11 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
12 Trả về
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
13 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. Hiện tại, cách duy nhất để 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 là kế thừa hỗn hợp, khai báo
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 với một giá trị cho đối số
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
91 và sau đó kế thừa nó từ một
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13 khác với giá trị khác với
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
91. Cách sử dụng:

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] # typechecks; 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.8.

Bộ sưu tập bê tông chung chung(dict, MutableMapping[KT, VT])

Tương ứng với các loại tích hợp

Lớp ________ 221 ________ 521 (Dict, Mutablemapping [KT, VT]) ¶

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

Một phiên bản chung của
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
83. 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)
23.(list, MutableSequence[T])

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

Lớp ________ 221 ________ 525 (Danh sách, Mutablesequence [T]) ¶

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

Phiên bản chung của
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
26. 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)
27 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:
    ...
11.(set, MutableSet[T])

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

Lớp ________ 221 ________ 530 (Set, Mutableset [T]) ¶(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)
31. 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)
32.

Lớp ________ 221 ________ 534 (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)
35.

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:
    ...
37 là một hình thức đặc biệt.(collections.defaultdict, MutableMapping[KT, VT])

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

Lớp ________ 221 ________ 539 (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)
40.(collections.OrderedDict, MutableMapping[KT, VT])

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

Lớp ________ 221 ________ 542 (Bộ sưu tập

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

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

Lớp ________ 221 ________ 545 (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)
46.

Mới trong phiên bản 3.5.4.(collections.Counter, Dict[T, int])

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

Lớp ________ 221 ________ 545 (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)
46.

Mới trong phiên bản 3.5.4.(deque, MutableSequence[T])

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

Lớp ________ 221 ________ 545 (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)
46.

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

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

Lớp ________ 221 ________ 548 (Bộ sưu tập. Chuỗi, Dict [T, Int])

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
49.The
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
63 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
07 instead.

Lớp ________ 221 ________ 551 (Deque, Mutablesequence [T]) ¶

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

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

Các loại bê tông khácThe

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
76 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
07 instead.

Lớp ________ 221 ________ 554¶ Lớp ________ 221 ________ 556¶ Lớp ________ 221 ________ 558¶Classes

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
78 and
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
79 from
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
80 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:
    ...
17. See PEP 585 and Generic Alias Type.

Loại chung
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
59 và các lớp con của nó
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
60 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
61 đạ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)
62.

Không dùng nữa kể từ phiên bản 3.8, sẽ bị xóa trong phiên bản 3.12: không gian tên

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
63 bị không dùng và sẽ bị xóa. Thay vào đó, các loại này nên được nhập trực tiếp từ
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
07.

Lớp ________ 221 ________ 566¶ Lớp ________ 221 ________ 568¶

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

Lớp ________ 221 ________ 539 (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) 40.

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

Lớp ________ 221 ________ 542 (Bộ sưu tập(Sized, Collection[T_co])

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

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

Mới trong phiên bản 3.7.2.(Sequence[int])

Lớp ________ 221 ________ 545 (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)
46.

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

Mới trong phiên bản 3.6.1.(Sized, Iterable[T_co], Container[T_co])

Lớp ________ 221 ________ 548 (Bộ sưu tập. Chuỗi, Dict [T, Int])

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

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

Lớp ________ 221 ________ 551 (Deque, Mutablesequence [T]) ¶(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 typecheck
class AdminUserId(UserId): pass
05.

Lớp ________ 221 ________ 607 (ánh xạview, chung [KT_CO, VT_CO]) ¶(MappingView, Generic[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 typecheck
class AdminUserId(UserId): pass
08.

Lớp ________ 221 ________ 610 (Bản đồView [KT_CO], Tóm tắt [KT_CO]) ¶(MappingView[KT_co], 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 typecheck
class AdminUserId(UserId): pass
11.

Lớp ________ 221 ________ 613 (có kích thước, bộ sưu tập [kt], chung [vt_co]) ¶(Sized, Collection[KT], Generic[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 typecheck
class AdminUserId(UserId): pass
14. Loại này có thể được sử dụng như sau:

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

Lớp ________ 221 ________ 616 (có kích thước, có thể lặp lại [T_CO]) ¶(Sized, 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 typecheck
class AdminUserId(UserId): pass
17.

Lớp ________ 221 ________ 619 (ánh xạ [kt, vt]) ¶(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 typecheck
class AdminUserId(UserId): pass
20.

Lớp ________ 221 ________ 622 (Chuỗi [T])(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 typecheck
class AdminUserId(UserId): pass
23.

Lớp ________ 221 ________ 625 (Tóm tắt [T]) ¶(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 typecheck
class AdminUserId(UserId): pass
26.

Lớp ________ 221 ________ 628 (có thể đảo ngược [T_CO], Bộ sưu tập [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
29.

Lớp ________ 221 ________ 631 (Bản đồview [VT_CO]) ¶(MappingView[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 typecheck
class AdminUserId(UserId): pass
32.

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

Lớp ________ 221 ________ 635 (chung [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
36.

Lớp ________ 221 ________ 638 (Itable [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
39.

Lớp ________ 221 ________ 641 (iterator [t_co], chung [t_co, t_contra, v_co]) ¶(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 typecheck
class AdminUserId(UserId): pass
42. 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
4

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 typecheck
class AdminUserId(UserId): pass
43 của
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
44 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 sẽ 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 typecheck
class AdminUserId(UserId): pass
43 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:
    ...
61 thành
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26:

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

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 typecheck
class AdminUserId(UserId): pass
48 hoặc
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
49:

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

Lớp ________ 221 ________ 651¶

Một bí danh đến

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
52.

Lớp ________ 221 ________ 654 (Itable [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
55.

Lớp ________ 221 ________ 657¶

Một bí danh đến

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
58.

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

Lớp ________ 221 ________ 660 (có thể chờ đợi [V_CO], chung [T_CO, T_Contra, V_CO])(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 typecheck
class AdminUserId(UserId): pass
61. 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 typecheck
class AdminUserId(UserId): pass
44, 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
7

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

Lớp ________ 221 ________ 664 (Asynciterator [T_CO], Generic [T_CO, T_Contra]) ¶(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 typecheck
class AdminUserId(UserId): pass
65. 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
8

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:
    ...
61. Như với
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
44,
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
43 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 typecheck
class AdminUserId(UserId): pass
43 thành
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26:

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

Ngoài ra, hãy 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 typecheck
class AdminUserId(UserId): pass
71 hoặc
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
72:

from collections.abc import Mapping, Sequence

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

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

Lớp ________ 221 ________ 674 (chung [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
75.

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

Lớp ________ 221 ________ 677 (không đồng bộ [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
78.

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

Lớp ________ 221 ________ 677 (không đồng bộ [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
78.

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

Lớp ________ 221 ________ 677 (không đồng bộ [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 typecheck
class AdminUserId(UserId): pass
78.(Generic[T_co])

Lớp ________ 221 ________ 680 (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 typecheck
class AdminUserId(UserId): pass
81.

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

Lớp ________ 221 ________ 683 (chung [T_CO]) ¶(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 typecheck
class AdminUserId(UserId): pass
84.

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

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
81.

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

Lớp ________ 221 ________ 683 (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 typecheck
class AdminUserId(UserId): pass
84.

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

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

Lớp ________ 221 ________ 686 (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 typecheck
class AdminUserId(UserId): pass
87.

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

Giao thức

Các giao thức này được trang trí với
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
49.

Lớp ________ 221 ________ 690¶

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 typecheck
class AdminUserId(UserId): pass
91 là hiệp phương sai trong loại trả lại của nó.

Lớp ________ 221 ________ 693¶

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 typecheck
class AdminUserId(UserId): pass
94.

Lớp ________ 221 ________ 696¶

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 typecheck
class AdminUserId(UserId): pass
97.

Lớp ________ 221 ________ 699¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

Lớp ________ 221 ________ 702¶

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

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
03.(typ, val)

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

Lớp ________ 221 ________ 705¶

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

UserId = NewType('UserId', int)

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

Lớp ________ 221 ________ 708¶

from collections.abc import Mapping, Sequence

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

Xem PEP 484 để biết chi tiết và so sánh với các ngữ nghĩa đánh máy khác.PEP 484 for details and comparison with other typing semantics.

________ 450 ________ 221 ________ 724¶

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ụ:

from collections.abc import Mapping, Sequence

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

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.

________ 450 ________ 221 ________ 727¶

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 đượ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 lớp con của nó).decorator. With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses).

Điều này làm thay đổi (các) hàm tại chỗ.

________ 450 ________ 221 ________ 730¶

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)
31.

Đ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)
31.

________ 450 ________ 221 ________ 735¶

Người trang trí để đánh dấu một lớp học hoặc chức năng không có sẵn trong thời gian chạy.

Trang trí này tự nó không có sẵn trong thời gian chạy. Nó chủ yếu nhằm đánh dấu các lớp được xác định trong các tệp sơ khai loại nếu việc triển khai trả về một thể hiện của một lớp riêng:

from collections.abc import Mapping, Sequence

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

Lưu ý rằng các trường hợp trả lại của các lớp tư nhân không được khuyến khích. Nó thường tốt hơn để làm cho các lớp học như vậy công khai.

Người trợ giúp nội tâm

________ 221 ________ 737 (obj, globalns = none, localns = none(obj, globalns=None, localns=None, include_extras=False)

Trả về một từ điển chứa các gợi ý loại cho một hàm, phương thức, mô -đun hoặc đối tượng lớp.

Điều này thường giống như

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
38. Ngoài ra, các tài liệu tham khảo chuyển tiếp được mã hóa dưới dạng chữ cái được xử lý bằng cách đánh giá chúng trong các không gian tên
from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
40. Nếu cần thiết,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
41 đượ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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26 được đặt. Đối với 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:
    ...
90, hãy trả về một từ điển được xây dựng bằng cách hợp nhất tất cả
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
68 dọc theo
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
45 theo thứ tự ngược lại.

Hàm thay thế đệ quy tất cả

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
46 bằng
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63, trừ khi
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
48 được đặt thành
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
54 (xem
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16 để biết thêm thông tin). Ví dụ:

from collections.abc import Mapping, Sequence

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

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
41 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)
48 như là một phần của PEP 593.Added
from typing import NewType

UserId = NewType('UserId', int)

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

________ 221 ________ 754 (TP) ____ ____ 221 ________ 756 (TP) ¶(tp)
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:
    ...
21
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
56(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)
57, các chức năng này trả về
from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
58 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)
37, 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)
58 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 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)
59 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)
65 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
67 tương ứng. Ví dụ:

from collections.abc import Mapping, Sequence

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

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

________ 450 ________ 221 ________ 727¶(tp)

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 đượ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 lớp con của nó).

from collections.abc import Mapping, Sequence

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

Điều này làm thay đổi (các) hàm tại chỗ.

________ 450 ________ 221 ________ 730¶

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)
31.

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
41 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. generic types such as
from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

Đã 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)
48 như là một phần của PEP 593.

________ 221 ________ 754 (TP) ____ ____ 221 ________ 756 (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)
57, các chức năng này trả về
from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
58 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)
37, 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)
58 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12 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)
59 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)
65 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]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
67 tương ứng. Ví dụ:

from collections.abc import Mapping, Sequence

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

________ 221 ________ 769 (TP) ¶

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
41 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.PEP 563).

Đã 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)
48 như là một phần của PEP 593.

Chúng ta có cần chỉ định loại dữ liệu trong Python không?

Python là một ngôn ngữ được gõ động, có nghĩa là chúng ta không phải chỉ định các loại dữ liệu khi chúng ta tạo các biến và hàm. Mặc dù điều này làm giảm lượng mã chúng ta cần viết, khối lượng công việc mà chúng ta lưu lần lượt được thêm vào nhà phát triển tiếp theo cần hiểu và gỡ lỗi chức năng hiện có!we don't have to specify data types when we create variables and functions. While this reduces the amount of code we need to write, the workload that we save is in turn added to the next developer that needs to understand and debug the existing function!

Bạn có thể chỉ định loại trong Python không?

Các phiên bản gần đây của Python cho phép bạn chỉ định các gợi ý loại rõ ràng có thể được sử dụng bởi các công cụ khác nhau để giúp bạn phát triển mã của mình hiệu quả hơn.Trong hướng dẫn này, bạn sẽ tìm hiểu về những điều sau: Loại chú thích và gợi ý loại.Thêm các loại tĩnh vào mã, cả mã của bạn và mã của người khác. that can be used by different tools to help you develop your code more efficiently. In this tutorial, you'll learn about the following: Type annotations and type hints. Adding static types to code, both your code and the code of others.

Làm thế nào để bạn xác định một loại trong Python?

Loại python ()..
loại () cú pháp.Hàm loại () có hai dạng khác nhau: Loại # với loại tham số đơn (đối tượng) # Loại với 3 loại tham số (tên, cơ sở, dict).
loại () tham số.Hàm loại () có một tham số đối tượng duy nhất.Hoặc, nó mất 3 tham số ..
loại () giá trị trả về.Hàm loại () trả về ..