Hướng dẫn do you need typing in python? - bạn có cần gõ vào python không?

Trong bài học này, bạn sẽ khám phá những ưu và nhược điểm của gợi ý loại. Trong bài học trước, bạn đã xem qua loại kiểm tra trong Python trông như thế nào. Dưới đây là một số lợi thế của gợi ý loại:type hints. In the previous lesson, you took a peek into what type checking in Python looks like. Here are some of the advantages of type hints:

Show
  • Nhập gợi ý giúp nắm bắt một số lỗi nhất định, như bạn đã thấy trong bài học trước.catch certain errors, as you saw in the previous lesson.

  • Nhập gợi ý giúp ghi lại mã của bạn. Theo truyền thống, bạn sẽ sử dụng DocStrings nếu bạn muốn ghi lại các loại dự kiến ​​của một đối số chức năng. Điều này hoạt động, nhưng vì không có tiêu chuẩn cho DocStrings (mặc dù PEP 257), chúng có thể dễ dàng sử dụng để kiểm tra tự động.document your code. Traditionally, you would use docstrings if you wanted to document the expected types of a function’s arguments. This works, but as there is no standard for docstrings (despite PEP 257), they can’t be easily used for automatic checks.

  • Loại gợi ý cải thiện IDE và linters. Họ làm cho nó dễ dàng hơn nhiều để có lý do tĩnh về mã của bạn.improve IDEs and linters. They make it much easier to statically reason about your code.

  • Nhập gợi ý giúp bạn xây dựng và duy trì kiến ​​trúc sạch hơn. Hành động viết gợi ý loại buộc bạn phải suy nghĩ về các loại trong chương trình của bạn. Mặc dù bản chất năng động của Python là một trong những tài sản tuyệt vời của nó, có ý thức về việc dựa vào việc gõ vịt, các phương pháp quá tải hoặc nhiều loại trả lại là một điều tốt.build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program. While the dynamic nature of Python is one of its great assets, being conscious about relying on duck typing, overloaded methods, or multiple return types is a good thing.

Tất nhiên, kiểm tra loại tĩnh không phải là tất cả các đào và kem. Ngoài ra còn có một số nhược điểm bạn nên xem xét:

  • Loại gợi ý mất thời gian và nỗ lực của nhà phát triển. Mặc dù nó có thể được đền đáp trong việc dành ít thời gian để gỡ lỗi, bạn sẽ dành nhiều thời gian hơn để nhập mã.take developer time and effort to add. Even though it probably pays off in spending less time debugging, you will spend more time entering code.

  • Loại gợi ý hoạt động tốt nhất trong trăn hiện đại. Các chú thích đã được giới thiệu trong Python 3.0, và nó có thể sử dụng các nhận xét loại trong Python 2.7. Tuy nhiên, các cải tiến như chú thích thay đổi và đánh giá các gợi ý loại có nghĩa là bạn sẽ có trải nghiệm tốt hơn khi kiểm tra loại bằng Python 3.6 hoặc thậm chí là Python 3.7.work best in modern Pythons. Annotations were introduced in Python 3.0, and it’s possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you’ll have a better experience doing type checks using Python 3.6 or even Python 3.7.

  • Loại gợi ý giới thiệu một hình phạt nhẹ trong thời gian khởi nghiệp. Nếu bạn cần sử dụng mô -đun

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    24, thì thời gian nhập có thể là đáng kể, đặc biệt là trong các tập lệnh ngắn.introduce a slight penalty in start-up time. If you need to use the
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    24 module, then the import time may be significant, especially in short scripts.

Bạn có nên sử dụng kiểm tra loại tĩnh trong mã của riêng bạn không? Nó không phải là một câu hỏi tất cả hoặc không có gì. Python hỗ trợ khái niệm gõ dần dần. Điều này có nghĩa là bạn có thể dần dần đưa các loại vào mã của mình. Mã không có gợi ý loại sẽ bị bỏ qua bởi trình kiểm tra loại tĩnh. Do đó, bạn có thể bắt đầu thêm các loại vào các thành phần quan trọng và tiếp tục miễn là nó thêm giá trị cho bạn.

Dưới đây là một vài quy tắc về việc có nên thêm các loại vào dự án của bạn:

  • Nếu bạn chỉ bắt đầu học Python, bạn có thể chờ đợi một cách an toàn với các gợi ý cho đến khi bạn có nhiều kinh nghiệm hơn.

  • Loại gợi ý thêm ít giá trị trong các kịch bản ném ngắn.

  • Trong các thư viện sẽ được sử dụng bởi những người khác, đặc biệt là các thư viện được xuất bản trên PYPI, gõ gợi ý thêm rất nhiều giá trị. Mã khác sử dụng thư viện của bạn cần các gợi ý loại này để tự kiểm tra đúng. Để biết các ví dụ về các dự án sử dụng gợi ý loại, xem

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    25,
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    26, đầu đọc Python thực sự của chúng tôi và chính MyPy.

  • Trong các dự án lớn hơn, các gợi ý loại giúp bạn hiểu cách các loại chảy qua mã của bạn và rất được khuyến khích, tất cả đều như vậy trong các dự án mà bạn hợp tác với người khác.

Trong bài viết xuất sắc của mình, trạng thái của các gợi ý loại trong Python, Bernátbor đề nghị rằng nên sử dụng gợi ý loại của loại bất cứ khi nào các bài kiểm tra đơn vị đáng để viết. Thật vậy, gõ gợi ý đóng một vai trò tương tự như các bài kiểm tra trong mã của bạn: chúng giúp bạn như một nhà phát triển viết mã tốt hơn.

Chú thích loại đầu tiên phải được đặt trong các trích dẫn, làm cho nó trở thành một tài liệu tham khảo phía trước, để ẩn tham chiếu from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId) 72 từ thời gian chạy của trình thông dịch. Loại chú thích cho các biến cục bộ không được đánh giá, vì vậy chú thích thứ hai không cần phải được đặt trong các trích dẫn.

Nếu
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
73 được sử dụng, các chú thích không được đánh giá theo thời gian định nghĩa chức năng. Thay vào đó, chúng được lưu trữ dưới dạng chuỗi trong
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
95. Điều này làm cho việc sử dụng các trích dẫn xung quanh chú thích không cần thiết (xem PEP 563).

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

Gỡ lỗi dễ dàng hơn: Nếu bây giờ nó không rõ ràng. Sử dụng các gợi ý loại có thể giúp việc gỡ lỗi dễ dàng hơn nhiều trong mã của bạn và trong rất nhiều trường hợp có thể hoàn toàn tránh được một số lỗi, đặc biệt nếu được sử dụng với trình kiểm tra loại tĩnh như MyPy.

Mới trong phiên bản 3.5. Lib/typing.py

Mã nguồn: lib/gõ.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.PEP 484. For a simplified introduction to type hints, see PEP 483.

Mô -đun này cung cấp hỗ trợ thời gian chạy cho các gợi ý loại. Hỗ trợ cơ bản nhất bao gồm các loại

Vector = list[float]

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

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

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

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

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

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

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

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

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

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

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

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

Trong hàm

Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
33 dự kiến ​​sẽ thuộc loại
Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34. Các kiểu con được chấp nhận là đối số.

Các tính năng mới thường được thêm vào mô -đun

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36. Gói typing_extensions cung cấp các bản sao của các tính năng mới này cho các phiên bản Python cũ hơn.

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

Xem thêm

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

Peps¶ có liên quanPEP 484 and PEP 483, a number of PEPs have modified and enhanced Python’s framework for type annotations. These include:

  • 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:: Syntax for Variable Annotations

    PEP 526: Cú pháp để chú thích biến

  • Giới thiệu cú pháp để chú thích các biến bên ngoài các định nghĩa chức năng và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    37
    : Protocols: Structural subtyping (static duck typing)

    PEP 544: Các giao thức: Substing cấu trúc (gõ vịt tĩnh)

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    38 và người trang trí
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    39
    : Type Hinting Generics In Standard Collections

    PEP 585: Loại Generics Generics trong các bộ sưu tập tiêu chuẩngeneric types

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    40 và khả năng sử dụng các lớp thư viện tiêu chuẩn làm loại chung
    : Literal Types

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

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    41
    : TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys

    PEP 589: TypedDict: Loại gợi ý cho từ điển với một bộ khóa cố định

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    42
    : Adding a final qualifier to typing

    PEP 591: Thêm một vòng loại cuối cùng để đánh máy

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    43 và người trang trí
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    44
    : Flexible function and variable annotations

    PEP 593: Chức năng linh hoạt và Chú thích thay đổi

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    45
    : Allow writing union types as
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    46

    PEP 604: Cho phép viết các loại liên minh là

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    46union of types

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    47 và khả năng sử dụng toán tử nhị phân
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    48 để biểu thị sự kết hợp của các loại
    : Parameter Specification Variables

    PEP 612: Biến đặc tả tham số

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    49 và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    50
    : Explicit Type Aliases

    PEP 613: Bí danh loại rõ ràng

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    51
    : Variadic Generics

    PEP 646: Generics Variadic

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    52
    : User-Defined Type Guards

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

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    53
    : Marking individual TypedDict items as required or potentially missing

    PEP 655: Đánh dấu các mục cá nhân đánh máy theo yêu cầu hoặc có khả năng bị thiếu

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    54 và
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    55
    : Self type

    PEP 673: Loại tự

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    56
    : Arbitrary Literal String Type

    PEP 675: Loại chuỗi theo nghĩa đen tùy ý

  • Giới thiệu
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    57
    : Data Class Transforms

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

Giới thiệu Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) 58 Trang trí

Gõ bí danh

Vector = list[float]

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

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

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

Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
60 sẽ được coi là từ đồng nghĩa có thể hoán đổi cho nhau:

from collections.abc import Sequence

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

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

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

Bí danh loại rất hữu ích để đơn giản hóa chữ ký loại phức. Ví dụ:

Lưu ý rằng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) 61 dưới dạng gợi ý loại là một trường hợp đặc biệt và được thay thế bằng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) 62.

Kiểu mới¶

from typing import NewType

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

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

Vector = list[float]

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)

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:

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

Lưu ý rằng các kiểm tra này chỉ được thực thi bởi trình kiểm tra loại tĩnh. Trong thời gian chạy, câu lệnh

Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
71 có thể gọi được ngay lập tức trả về bất kỳ tham số nào bạn vượt qua. Điều đó có nghĩa là biểu thức
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
72 không tạo ra một lớp mới hoặc giới thiệu nhiều chi phí vượt ra ngoài cuộc gọi chức năng thông thường.

Chính xác hơn, biểu thức

Vector = list[float]

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

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

Nó không hợp lệ khi tạo một loại phụ của

Vector = list[float]

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

Tuy nhiên, có thể tạo ra một

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 dựa trên một ____ ____
Vector = list[float]

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

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)

và đánh máy cho

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
77 sẽ hoạt động như mong đợi.

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

Ghi chú

Hãy nhớ lại rằng việc sử dụng một bí danh loại tuyên bố hai loại tương đương với nhau. Thực hiện

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
78 sẽ làm cho trình kiểm tra loại tĩnh điều trị
Vector = list[float]

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
80 trong mọi trường hợp. Điều này rất hữu ích khi bạn muốn đơn giản hóa chữ ký loại phức tạp.

Ngược lại,

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 tuyên bố một loại là một loại phụ của loại khác. Thực hiện
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
82 sẽ làm cho trình kiểm tra loại tĩnh xử lý
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
71 dưới dạng lớp con của
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
80, có nghĩa là giá trị của loại
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
80 không thể được sử dụng ở những nơi dự kiến ​​giá trị của loại
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
71. Điều này rất hữu ích khi bạn muốn ngăn chặn các lỗi logic với chi phí thời gian chạy tối thiểu.

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 hiện là một lớp chứ không phải là một hàm. Có một số chi phí thời gian chạy bổ sung khi gọi
Vector = list[float]

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 is now a class rather than a function. There is some additional runtime cost when calling
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63 over a regular function. However, this cost will be reduced in 3.11.0.

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

Các khung mong đợi các chức năng gọi lại của chữ ký cụ thể có thể được loại gợi ý bằng cách sử dụng

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
89.

Ví dụ:

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update

Có thể khai báo loại trả về của một cuộc gọi có thể gọi mà không chỉ định chữ ký cuộc gọi bằng cách thay thế một dấu chấm lửng theo nghĩa đen cho danh sách các đối số trong loại gợi ý:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
90.

Các thiết bị gọi lấy các thiết bị gọi khác làm đối số có thể chỉ ra rằng các loại tham số của chúng phụ thuộc vào nhau bằng cách sử dụng

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49. Ngoài ra, nếu có thể gọi được thêm hoặc xóa các đối số khỏi các loại gọi khác, toán tử
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
50 có thể được sử dụng. Họ lần lượt nhận dạng
Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
94.

Thuốc generics;

Vì thông tin loại về các đối tượng được giữ trong các container không thể được suy ra tĩnh một cách chung, nên các lớp cơ sở trừu tượng đã được mở rộng để hỗ trợ đăng ký để biểu thị các loại dự kiến ​​cho các yếu tố container.

from collections.abc import Mapping, Sequence

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

Generics có thể được tham số hóa bằng cách sử dụng một nhà máy có sẵn trong việc gõ gọi là

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
30.

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
0

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

Một lớp do người dùng xác định có thể được định nghĩa là một lớp chung.

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
1

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
96 Là một lớp cơ sở định nghĩa rằng lớp
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
97 có một tham số loại duy nhất
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
98. Điều này cũng làm cho
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
98 có giá trị như một loại trong cơ thể lớp.

Lớp cơ sở

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31 xác đị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:
    ...
01 để
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
02 hợp lệ dưới dạng loại:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
2

Một loại chung có thể có bất kỳ số lượng biến loại. Tất cả các giống

Vector = list[float]

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
3

Mỗi đối số biến loại thành

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31 phải khác biệt. Điều này không hợp lệ:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
4

Bạn có thể sử dụng nhiều kế thừa với

Vector = list[float]

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
5

Khi kế thừa từ các lớp chung, một số biến loại có thể được sửa:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
6

Trong trường hợp này

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
06 có một tham số duy nhất,
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
98.

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 cho mỗi vị trí. Trong ví dụ sau,
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
09 không chung chung mà là kế thừa ngầm từ
from collections.abc import Sequence

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

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
7

Bí danh loại chung được xác định của người dùng cũng được hỗ trợ. Ví dụ:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
8

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31 không còn có Metaclass tùy chỉnh.
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31 no longer has a custom metaclass.

Generics do người dùng xác định cho các biểu thức tham số cũng được hỗ trợ thông qua các biến đặc tả tham số ở dạng

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
12. Hành vi phù hợp với các biến loại, được mô tả ở trên là các biến đặc tả tham số được coi bởi mô -đun gõ là một biến loại chuyên dụng. Một ngoại lệ cho điều này là một danh sách các loại có thể được sử dụng để thay thế một
Vector = list[float]

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
9

Hơn nữa, một chung chỉ có một biến đặc tả tham số sẽ chấp nhận danh sách tham số trong các biểu mẫu

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
14 và cũng
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
15 vì lý do thẩm mỹ. Trong nội bộ, cái sau được chuyển đổi thành cái trước, vì vậy những điều sau đây là tương đương:

from collections.abc import Sequence

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

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

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

Xin lưu ý rằng các chất generic với

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 có thể không đúng
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
17 sau khi thay thế trong một số trường hợp vì chúng được dự định chủ yếu để kiểm tra loại tĩnh.

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31 hiện có thể được tham số hóa qua các biểu thức tham số. Xem
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 và PEP 612 để biết thêm chi tiết.
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31 can now be parameterized over parameter expressions. See
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 and PEP 612 for more details.

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

Loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) 27

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27. Một trình kiểm tra loại tĩnh sẽ coi mọi loại là tương thích với
Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 là tương thích với mọi loại.

Điều này có nghĩa là có thể thực hiện bất kỳ hoạt động hoặc phương thức gọi trên giá trị của loại

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 và gán nó cho bất kỳ biến nào:

from collections.abc import Sequence

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

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

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

Lưu ý rằng không có kiểm tra loại nào được thực hiện khi gán giá trị loại

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 cho loại chính xác hơn. Ví dụ: Trình kiểm tra loại tĩnh đã không báo cáo lỗi khi gán
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
26 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:
    ...
27 mặc dù
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
27 đã được tuyên bố là loại
Vector = list[float]

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

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

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

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

Vector = list[float]

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

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

from collections.abc import Sequence

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

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

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

Hành vi này cho phép

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 được sử dụng như một cửa thoát hiểm khi bạn cần kết hợp mã được gõ linh hoạt và thống kê.

Tương phản hành vi của

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 với hành vi của
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
34. Tương tự như
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27, mọi loại là một loại phụ của
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
34. Tuy nhiên, không giống như
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27, điều ngược lại không đúng:
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
34 không phải là một kiểu con của mọi loại khác.

Điều đó có nghĩa là khi loại giá trị là

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
34, trình kiểm tra loại sẽ từ chối hầu hết tất cả các hoạt động trên đó và gán nó cho một biến (hoặc sử dụng nó làm giá trị trả về) của một loại chuyên dụng hơn là lỗi loại. Ví dụ:

from collections.abc import Sequence

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

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

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

Sử dụng

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
34 để chỉ ra rằng giá trị có thể là bất kỳ loại nào theo cách kiểu an toàn. Sử dụng
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 để 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:
    ...
42 đượ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:
    ...
43 đượ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:
    ...
42 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:
    ...
43.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:
    ...
42 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:
    ...
43 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:
    ...
42 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:
    ...
43.

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:
    ...
46. 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:
    ...
47 đượ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:
    ...
47 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:
    ...
48 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:
    ...
49 by static type checkers. This is known as structural subtyping (or static duck-typing):

from collections.abc import Sequence

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

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

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

Hơn nữa, bằng cách phân lớp một lớp đặc biệt

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
38, người dùng có thể xác định các giao thức tùy chỉnh mới để thưởng thức hoàn toàn phân nhóm cấu trúc (xem các ví dụ bên dưới).

Nội dung mô -đun

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

Ghi chú

Mô-đun này xác định một số loại là các lớp con của các lớp thư viện tiêu chuẩn có sẵn cũng mở rộng

Vector = list[float]

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

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

Các loại dự phòng không được chấp nhận kể từ Python 3.9 nhưng không có cảnh báo phản đối nào sẽ được đưa ra bởi thông dịch viên. Dự kiến ​​các trình kiểm tra loại sẽ gắn cờ các loại không dùng nữa khi chương trình được kiểm tra nhắm mục tiêu Python 3.9 hoặc mới hơn.

Các loại không dùng sẽ được xóa khỏi mô -đun

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36 trong phiên bản Python đầu tiên được phát hành 5 năm sau khi phát hành Python 3.9.0. Xem chi tiết trong PEP 585, Generics Generics trong các bộ sưu tập tiêu chuẩn.PEP 585—Type Hinting Generics In Standard Collections.

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

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

Chúng có thể được sử dụng dưới dạng các loại trong các chú thích và không hỗ trợ

from collections.abc import Sequence

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

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

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

gõ.Any

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

  • Mỗi loại tương thích với

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    27.

  • Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    27 tương thích với mọi loại.

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 hiện có thể được sử dụng làm lớp cơ sở. Điều này có thể hữu ích để tránh các lỗi kiểm tra loại với các lớp có thể loại vịt ở bất cứ đâu hoặc rất năng động.
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
27 can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

Gõ.LiteralString

Loại đặc biệt chỉ bao gồm các chuỗi theo nghĩa đen. Một chuỗi theo nghĩa đen tương thích với

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
57, như một
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
57 khác, nhưng một đối tượng được gõ là
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34 thì không. Một chuỗi được tạo bằng cách soạn thảo các đối tượng gy ____ 157 cũng được chấp nhận dưới dạng
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
57.

Example:

from collections.abc import Sequence

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

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

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

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

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

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

gõ. Không bao giờNever

Loại dưới cùng, một loại không có thành viên.

Điều này có thể được sử dụng để xác định một hàm không bao giờ được gọi hoặc một hàm không bao giờ trả về:

from collections.abc import Sequence

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

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

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

Mới trong phiên bản 3.11: Trên các phiên bản Python cũ hơn,

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
64 có thể được sử dụng để thể hiện cùng một khái niệm.
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
65 đã được thêm vào để làm cho ý định có ý nghĩa rõ ràng hơn.On older Python versions,
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
64 may be used to express the same concept.
from collections.abc import Sequence

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

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

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

Gõ.Noreturn¶NoReturn

Loại đặc biệt chỉ ra rằng một hàm không bao giờ trả về. Ví dụ:

from collections.abc import Sequence

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

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

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
64 cũng có thể được sử dụng như một loại dưới cùng, một loại không có giá trị. Bắt đầu trong Python 3.11, loại
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
65 nên được sử dụng cho khái niệm này. Loại kiểm tra nên đối xử với hai người tương đương.

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

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

gõ.SelfSelf

Loại đặc biệt để đại diện cho lớp kèm theo hiện tại. Ví dụ:

from collections.abc import Sequence

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

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

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

Chú thích này tương đương về mặt ngữ nghĩa với những điều sau đây, mặc dù theo kiểu cô đọng hơn:

from typing import NewType

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

Nói chung nếu một cái gì đó hiện đang tuân theo mô hình của:

from typing import NewType

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

Bạn nên sử dụng

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
56 làm cuộc gọi đến
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
69 sẽ có
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
70 dưới dạng loại trả về chứ không phải
from collections.abc import Sequence

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

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

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

Các trường hợp sử dụng phổ biến khác bao gồm:

  • from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message(message: str, servers: Sequence[Server]) -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message(
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
        ...
    
    72s được sử dụng làm hàm tạo thay thế và các phiên bản trả về của tham số
    from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message(message: str, servers: Sequence[Server]) -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message(
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
        ...
    
    73.

  • Chú thích một phương thức

    from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message(message: str, servers: Sequence[Server]) -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message(
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
        ...
    
    74 trả về bản thân.

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

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

gõ.typealias¶TypeAlias

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

from typing import NewType

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

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

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

Mẫu đặc biệt

Chúng có thể được sử dụng làm loại trong các chú thích bằng cách sử dụng

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
52, mỗi loại có một cú pháp duy nhất.

Gõ.Tuple¶Tuple

Loại tuple;

from collections.abc import Sequence

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

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

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

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:
    ...
78 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:
    ...
79 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:
    ...
80. 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:
    ...
81 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:
    ...
82, 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:
    ...
83.

gõ.Union¶Union

Loại công đoàn;

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
84 tương đương với
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
46 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:
    ...
86 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:
    ...
87. Sử dụng tốc ký đó được khuyến khích. Thông tin chi tiết:

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

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

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

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

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

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

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

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

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

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

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    28.

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

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

gõ.optional¶Optional

Loại tùy chọn.

from collections.abc import Sequence

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

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

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

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:
    ...
93 về chú thích loại của nó chỉ vì nó là tùy chọn. Ví dụ:

from typing import NewType

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

Mặt khác, nếu đượ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]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
61, 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:
    ...
93 là phù hợp, cho dù đối số có phải là tùy chọn hay không. Ví dụ:

from typing import NewType

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

Đã thay đổi trong phiên bản 3.10: Tùy chọn hiện có thể được viết là

from collections.abc import Sequence

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

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

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

Gõ.Callable

Loại có thể gọi được;

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
97 là một hàm của (int) -> str.

Cú pháp đăng ký phải luôn được sử dụng với chính xác hai giá trị: danh sách đối số và loại trả về. Danh sách đối số phải là danh sách các loại hoặc dấu chấm lửng; Loại trả về phải là một loại duy nhất.

Không có cú pháp để chỉ ra các đối số từ khóa hoặc tùy chọn; Các loại chức năng như vậy hiếm khi được sử dụng làm loại gọi lại.

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
90 (Ellipsis theo nghĩa đen) có thể được sử dụng để nhập gợi ý về việc gọi có thể gọi 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:
    ...
99. Một đơn vị
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
29 tương đương với
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
01, và lần lượt
from typing import NewType

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

Các thiết bị gọi lấy các thiết bị gọi khác làm đối số có thể chỉ ra rằng các loại tham số của chúng phụ thuộc vào nhau bằng cách sử dụng

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49. Ngoài ra, nếu có thể gọi được thêm hoặc xóa các đối số khỏi các loại gọi khác, toán tử
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
50 có thể được sử dụng. Họ lần lượt nhận dạng
Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
94.

gõ.concatenate¶Concatenate

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

Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 để nhập chú thích một thứ tự cao hơn có thể gọi có thể thêm, xóa hoặc biến đổi các tham số của một người khác có thể gọi được. Việc sử dụng ở dạng
from typing import NewType

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
50 hiện chỉ hợp lệ khi được sử dụng làm đối số đầu tiên cho
Vector = list[float]

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

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

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 hoặc Ellipsis (
from typing import NewType

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

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

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
16 cho chức năng được trang trí,
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
50 có thể được sử dụng để chỉ ra rằng
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
19 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. Trong trường hợp này,
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 chỉ ra rằng các loại tham số có thể gọi được trả về phụ thuộc vào các loại tham số của có thể gọi được được truyền vào:

from typing import NewType

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

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

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

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

classtyping.type (chung [ct_co]) ¶ typing.Type(Generic[CT_co])

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
25 có thể chấp nhận giá trị loại
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
25. Ngược lại, một biến được chú thích với
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
25. Ví dụ:

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
0

Lưu ý rằng

from typing import NewType

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
1

Thực tế là

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
27 là hiệp phương sai ngụ ý rằng tất cả các lớp con của
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
25 nên thực hiện cùng một chữ ký của hàm tạo và chữ ký phương pháp lớp là
from typing import NewType

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

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
33 là các lớp,
Vector = list[float]

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
2

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
35 tương đương với
from typing import NewType

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

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

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

Gõ.Literal¶Literal

Một loại có thể được sử dụng để chỉ ra các trình kiểm tra loại rằng biến hoặc tham số chức năng tương ứng có giá trị tương đương với nghĩa đen được cung cấp (hoặc một trong một số nghĩa đen). Ví dụ:

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
3

from typing import NewType

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

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
41 hiện đã khử trùng các tham số. So sánh bình đẳng của các đối tượng
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
41 không còn phụ thuộc vào thứ tự. Các đối tượng
Vector = list[float]

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

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

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

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

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

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

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

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

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

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

Gõ.Classvar¶ClassVar

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
4

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
37 chỉ chấp nhận các loại và không thể được đăng ký thêm.

Vector = list[float]

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

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
37 không thay đổi hành vi thời gian chạy Python, nhưng nó có thể được sử dụng bởi các trình kiểm tra loại bên thứ ba. Ví dụ: Trình kiểm tra loại có thể gắn cờ mã sau là lỗi:

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
5

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

gõ.final¶Final

Một cấu trúc gõ đặc biệt để chỉ ra để nhập trình kiểm tra rằng một tên không thể được gán lại hoặc ghi đè trong một lớp con. Ví dụ:

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
6

Không có kiểm tra thời gian chạy của các thuộc tính này. Xem PEP 591 để biết thêm chi tiết.PEP 591 for more details.

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

Đã thay đổi trong phiên bản 3.9.1:
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
41 hiện đã khử trùng các tham số. So sánh bình đẳng của các đối tượng
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
41 không còn phụ thuộc vào thứ tự. Các đối tượng
Vector = list[float]

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

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

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

Gõ.Classvar¶

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

Như được giới thiệu trong PEP 526, một chú thích thay đổi được bọc trong classvar chỉ ra rằng một thuộc tính nhất định được dự định sẽ được sử dụng làm biến lớp và không nên được đặt trên các trường hợp của lớp đó. Cách sử dụng:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
37 chỉ chấp nhận các loại và không thể được đăng ký thêm.
Annotated

Vector = list[float]

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

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
37 không thay đổi hành vi thời gian chạy Python, nhưng nó có thể được sử dụng bởi các trình kiểm tra loại bên thứ ba. Ví dụ: Trình kiểm tra loại có thể gắn cờ mã sau là lỗi:PEP 593 (
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
51), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as
Vector = list[float]

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

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

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

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

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

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
54, it should ignore it and simply treat the type as
Vector = list[float]

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

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36 module which completely disables typechecking annotations on a function or a class, the
Vector = list[float]

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

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

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

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

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

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

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

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]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
45 cho phép bạn đặt một số chú thích giống nhau (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:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
7

Chuyển

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
70 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 của

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    45 phải là loại hợp lệ

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

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    45 hỗ trợ các đối số variadic):

    def get_user_name(user_id: UserId) -> str:
        ...
    
    # passes type checking
    user_a = get_user_name(UserId(42351))
    
    # fails type checking; an int is not a UserId
    user_b = get_user_name(-1)
    
    8

  • Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    45 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)
    
    74 không hợp lệ)

  • Thứ tự của các chú thích được bảo tồn và các vấn đề để kiểm tra bình đẳng:

    def get_user_name(user_id: UserId) -> str:
        ...
    
    # passes type checking
    user_a = get_user_name(UserId(42351))
    
    # fails type checking; an int is not a UserId
    user_b = get_user_name(-1)
    
    9

  • Các loại

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    45 lồng nhau được làm phẳng, với siêu dữ liệu được đặt hàng bắt đầu với chú thích trong cùng:

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

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

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

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

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

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

gõ.typeguard¶TypeGuard

Biểu mẫu gõ đặc biệt được sử dụng để chú thích loại trả về của chức năng bảo vệ loại do người dùng xác định.

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
53 chỉ chấp nhận một đối số loại duy nhất. Trong thời gian chạy, các chức năng được đánh dấu theo cách này sẽ trả về Boolean.

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
53 nhằm mục đích thu hẹp loại lợi ích - Một kỹ thuật được sử dụng bởi các trình kiểm tra loại tĩnh để xác định một loại biểu thức chính xác hơn trong luồng mã chương trình. Thông thường thu hẹp loại được thực hiện bằng cách phân tích luồng mã có điều kiện và áp dụng việc thu hẹp vào một khối mã. Biểu thức có điều kiện ở đây đôi khi được gọi là một người bảo vệ kiểu người khác:

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

Đôi khi sẽ thuận tiện khi sử dụng chức năng Boolean do người dùng định nghĩa làm người bảo vệ loại. Một chức năng như vậy nên sử dụng

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
79 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)
80 nói với trình kiểm tra loại tĩnh rằng đối với một hàm đã cho:

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

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

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    81, loại đối số của nó là loại bên trong
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    53.

Ví dụ:

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

Nếu

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
83 là phương thức lớp hoặc phiên bản, thì loại trong
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
53 bản đồ theo loại tham số thứ hai sau
from collections.abc import Sequence

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

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

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

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

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

from typing import NewType

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

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

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

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

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

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

Ghi chú

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
96 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)
97 là bất biến. Trách nhiệm của việc viết bộ bảo vệ loại an toàn loại được để lại cho người dùng.

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
53 cũng hoạt động với các biến loại. Xem PEP 647 để biết thêm chi tiết.PEP 647 for more details.

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

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

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

classtyping.generic¶typing.Generic

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

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

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

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

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

classtyping.typevar¶typing.TypeVar

Loại biến.

Usage:

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31 để biết thêm thông tin về các loại chung. Chức năng chung hoạt động như sau:

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

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

Các biến loại ràng buộc và các biến loại bị ràng buộc có ngữ nghĩa khác nhau theo nhiều cách quan trọng. Sử dụng biến loại ràng buộc có nghĩa là

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
30 sẽ được giải quyết bằng cách sử dụng loại cụ thể nhất có thể:

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

Tuy nhiên, sử dụng một biến loại bị ràng buộc có nghĩa là

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
30 chỉ có thể được giải quyết là chính xác là một trong những ràng buộc đã đưa ra:

from typing import NewType

UserId = NewType('UserId', int)

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

Trong thời gian chạy,

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
02 sẽ tăng
from typing import NewType

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

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

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
06 hoặc
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
07. Xem PEP 484 để biết thêm chi tiết. Theo mặc định, các biến loại là bất biến.PEP 484 for more details. By default, type variables are invariant.

classtyping.typevartuple¶typing.TypeVarTuple

Loại biến tuple. Một hình thức chuyên dụng của

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
08 cho phép các chất generic variadic.

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
09 trong
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
10. Về mặt khái niệm, bạn có thể nghĩ
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
11 như một bộ biến loại
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
12.
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
10 sau đó sẽ trở thành
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
14, tương đương với
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
15. .

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

Cuối cùng, một loại biến loại chưa đóng gói có thể được sử dụng làm chú thích loại của

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
18:

from typing import NewType

UserId = NewType('UserId', int)

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

Trái ngược với các chú thích không được đóng gói của

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
18 - ví dụ:
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
20, trong đó sẽ chỉ định rằng tất cả các đối số là
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
64 -
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
22 cho phép tham chiếu đến các loại của các đối số riêng lẻ trong
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
18. Ở đây, điều này cho phép chúng tôi đảm bảo các loại của
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
18 được chuyển cho
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
25 khớp với các loại đối số (vị trí) của
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
26.

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

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

gõ.unpack¶Unpack

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
09 trên
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
28 tương đương với việc sử dụng
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
16 để đánh dấu loại biến loại đã được giải nén:

from typing import NewType

UserId = NewType('UserId', int)

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

Trên thực tế,

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
16 có thể được sử dụng thay thế cho
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
09 trong bối cảnh của các loại. Bạn có thể thấy
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
16 đang được sử dụng rõ ràng trong các phiên bản cũ của Python, trong đó
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
09 không thể được sử dụng ở một số nơi nhất định:

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
09 trên
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
28 tương đương với việc sử dụng
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
16 để đánh dấu loại biến loại đã được giải nén:

Usage:

Trên thực tế,

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
16 có thể được sử dụng thay thế cho
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
09 trong bối cảnh của các loại. Bạn có thể thấy
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
16 đang được sử dụng rõ ràng trong các phiên bản cũ của Python, trong đó
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
09 không thể được sử dụng ở một số nơi nhất định:

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
0

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
34.

  1. Các biến đặc tả tham số tồn tại chủ yếu vì lợi ích của bộ kiểm tra loại tĩnh. Chúng được sử dụng để chuyển tiếp các loại tham số của một người có thể gọi cho một người khác có thể gọi - một mẫu thường được tìm thấy trong các chức năng và bộ trang trí bậc cao. Chúng chỉ hợp lệ khi được sử dụng trong

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    50 hoặc là đối số đầu tiên với
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    29 hoặc làm tham số cho thuốc generic do người dùng xác định. Xem
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    31 để biết thêm thông tin về các loại chung.

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

    def get_user_name(user_id: UserId) -> str:
        ...
    
    # passes type checking
    user_a = get_user_name(UserId(42351))
    
    # fails type checking; an int is not a UserId
    user_b = get_user_name(-1)
    
    38 để ghi nhật ký các cuộc gọi chức năng. Biến đặc tả tham số cho biết trình kiểm tra loại rằng có thể gọi được chuyển vào trình trang trí và phần gọi mới được trả về bởi nó có các tham số loại phụ thuộc giữa các tham số:

Không có
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49, cách đơn giản nhất để chú thích điều này trước đây là sử dụng
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
30 với ràng buộc
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
01. Tuy nhiên, điều này gây ra hai vấn đề:
kwargs

Trình kiểm tra loại có thể loại kiểm tra hàm

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
42 vì
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
18 và
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
44 phải được gõ
Vector = list[float]

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
46 có thể được yêu cầu trong phần thân của bộ trang trí
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
38 khi trả lại hàm
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
42 hoặc trình kiểm tra loại tĩnh phải được yêu cầu bỏ qua
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
49.

Args¶ Kwargs¶

Vector = list[float]

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
51 và
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
51 đại diện cho bộ dữ liệu của các tham số vị trí trong một cuộc gọi nhất định và chỉ nên được sử dụng để chú thích
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
18.
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
52 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:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
44. Cả hai thuộc tính đều yêu cầu tham số chú thích phải nằm trong phạm vi. Trong thời gian chạy,
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
51 và
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
60 và
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
61.

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
06 hoặc
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
07 có thể được sử dụng để khai báo các loại chung hiệp phương sai hoặc contravariant. Đối số
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
64 cũng được chấp nhận, tương tự như
Vector = list[float]

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

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

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

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

Gõ.ParamSpecArgs¶ Gõ.ParamSpeckWargs¶ParamSpecArgstyping.ParamSpecKwargs

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
51 của
Vector = list[float]

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
60 và
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
61. 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:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
1

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

gõ.AnyStr¶AnyStr

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
78 là
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
80.

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)

ProUserId = NewType('ProUserId', UserId)
2

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

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
3

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
4

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
81 (được mô tả sau) đóng vai trò là các giao thức thời gian chạy có đầu óc đơn giản chỉ kiểm tra sự hiện diện của các thuộc tính đã cho, bỏ qua các chữ ký loại của chúng.PEP 544 for more details. Protocol classes decorated with
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
81 (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
5

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

@gõ.runtime_checkable¶typing.runtime_checkable

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

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

from typing import NewType

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
85, 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:
    ...
46. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
6

Ghi chú

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
81 sẽ chỉ kiểm tra sự hiện diện của các phương pháp cần thiết, không phải chữ ký loại của chúng. Ví dụ,
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
88 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)
47 đối với
Vector = list[float]

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
43 với một thông điệp nhiều thông tin hơn, do đó khiến nó không thể gọi (khởi tạo)
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
88.

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

@gõ.runtime_checkable¶

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

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

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
85, 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:
    ...
46. Ví dụ:
typing.NamedTuple

Ghi chú

Usage:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
7

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
81 sẽ chỉ kiểm tra sự hiện diện của các phương pháp cần thiết, không phải chữ ký loại của chúng. Ví dụ,
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
88 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)
47 đối với
Vector = list[float]

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
43 với một thông điệp nhiều thông tin hơn, do đó khiến nó không thể gọi (khởi tạo)
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
88.

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
8

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
9

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

classtyping.namedtuple¶

Phiên bản gõ của

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
94.

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update
0

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

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update
1

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

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update
2

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
95 đưa ra một dictor bản đồ tên trường thành các loại trường. .Added support for default values, methods, and docstrings.

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
01 and
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
95 attributes are now regular dictionaries instead of instances of
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
03.

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
99 Các lớp con có thể là chung chung:Removed the
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
01 attribute in favor of the more standard
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
95 attribute which has the same information.

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

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

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

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update
3

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
01 và
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
95 hiện là từ điển thường xuyên thay vì các trường hợp
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
03.

Đã thay đổi trong phiên bản 3.9: Đã xóa thuộc tính

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
01 có lợi cho thuộc tính
def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
95 tiêu chuẩn hơn có cùng thông tin.
Vector = list[float]

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

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

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

classtyping.newtype (tên, tp) ¶

Một lớp trợ giúp để chỉ ra một loại riêng biệt cho một typechecker, xem newtype. Khi chạy, nó trả về một đối tượng trả về đối số của nó khi được gọi. Cách sử dụng:

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update
4

Mới trong phiên bản 3.5.2.PEP 526,

Vector = list[float]

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

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

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

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    63 hiện là một lớp chứ không phải là một hàm.

    from collections.abc import Callable
    
    def feeder(get_next_item: Callable[[], str]) -> None:
        # Body
    
    def async_query(on_success: Callable[[int], None],
                    on_error: Callable[[int, Exception], None]) -> None:
        # Body
    
    async def on_update(value: str) -> None:
        # Body
    callback: Callable[[str], Awaitable[None]] = on_update
    
    5

  • classtyping.typeddict (dict) ¶

    from collections.abc import Callable
    
    def feeder(get_next_item: Callable[[], str]) -> None:
        # Body
    
    def async_query(on_success: Callable[[int], None],
                    on_error: Callable[[int, Exception], None]) -> None:
        # Body
    
    async def on_update(value: str) -> None:
        # Body
    callback: Callable[[str], Awaitable[None]] = on_update
    
    6

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 tuyên bố một loại từ điển hy vọng tất cả các trường hợp của nó sẽ có một bộ khóa nhất định, trong đó mỗi khóa được liên kết với giá trị của một loại nhất quán. Kỳ vọng này không được kiểm tra trong thời gian chạy nhưng chỉ được thực thi bởi người kiểm tra loại. Cách sử dụng:identifiers, for example because they are keywords or contain hyphens. Example:

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update
7

Theo mặc định, tất cả các khóa phải có mặt trong

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42. Có thể đánh dấu các khóa riêng lẻ là không yêu cầu bằng cách sử dụng
Vector = list[float]

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

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

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

Điều này có nghĩa là một

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
13
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 có thể có khóa
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
15 bị bỏ qua.

Cũng có thể đánh dấu tất cả các khóa là không được yêu cầu theo mặc định bằng cách chỉ định tổng số

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

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

Điều này có nghĩa là

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
13
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 có thể có bất kỳ khóa nào bị bỏ qua. Trình kiểm tra loại chỉ được dự kiến ​​sẽ hỗ trợ một
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
16 hoặc
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
81 theo nghĩa đen là giá trị của đối số
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
21.
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
81 là mặc định và làm cho tất cả các mục được xác định trong thân lớp cần thiết.

Các khóa riêng lẻ của

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
23
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 có thể được đánh dấu theo yêu cầu bằng cách sử dụng
Vector = list[float]

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

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

from collections.abc import Mapping, Sequence

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

Có thể loại

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 để kế thừa từ một hoặc nhiều loại
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 khác bằng cách sử dụng cú pháp dựa trên lớp. Cách sử dụng:

from collections.abc import Mapping, Sequence

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

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
54,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
30 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
31. Nó tương đương với định nghĩa này:

from collections.abc import Mapping, Sequence

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

A

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 không thể kế thừa từ một lớp không phải là -____ 142, ngoại trừ
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
31. Ví dụ:

from collections.abc import Mapping, Sequence

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

A

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 có thể là chung:

from collections.abc import Mapping, Sequence

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

A

Vector = list[float]

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

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

__toàn bộ__¶

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

from collections.abc import Mapping, Sequence

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

__required_keys__¶

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

__optional_keys__¶

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

Các khóa được đánh dấu bằng

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
54 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
38 và các khóa được đánh dấu bằng
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
55 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
39.

Đối với khả năng tương thích ngược với Python 3.10 trở xuống, cũng có thể sử dụng kế thừa để khai báo cả các khóa yêu cầu và không yêu cầu trong cùng một

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42. Điều này được thực hiện bằng cách khai báo
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 với một giá trị cho đối số
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
21 và sau đó kế thừa từ nó trong một
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 khác với giá trị khác với
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
21:

from collections.abc import Mapping, Sequence

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

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

__optional_keys__¶PEP 589 for more examples and detailed rules of using

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42.

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

Các khóa được đánh dấu bằng

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
54 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
38 và các khóa được đánh dấu bằng
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
55 sẽ luôn xuất hiện trong
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
39.Added support for marking individual keys as
Vector = list[float]

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
55. See PEP 655.

Đối với khả năng tương thích ngược với Python 3.10 trở xuống, cũng có thể sử dụng kế thừa để khai báo cả các khóa yêu cầu và không yêu cầu trong cùng một

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42. Điều này được thực hiện bằng cách khai báo
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 với một giá trị cho đối số
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
21 và sau đó kế thừa từ nó trong một
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 khác với giá trị khác với
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
21:Added support for generic
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42s.

Xem PEP 589 để biết thêm ví dụ và quy tắc chi tiết sử dụng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) 42.

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

Đã thay đổi trong phiên bản 3.11: Đã thêm hỗ trợ để đánh dấu các khóa riêng lẻ là
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
54 hoặc
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
55. Xem PEP 655.
typing.Dict(dict, MutableMapping[KT, VT])

Đã thay đổi trong phiên bản 3.11: Đã thêm hỗ trợ cho các

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42 chung.

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

from collections.abc import Mapping, Sequence

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

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

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

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

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

from collections.abc import Mapping, Sequence

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

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

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

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

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

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

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

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

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

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

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

Ghi chú

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
81 là một hình thức đặc biệt.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
77 namespace is deprecated and will be removed. These types should be directly imported from
Vector = list[float]

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

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

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

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

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

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

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
36.The
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
86 namespace is deprecated and will be removed. These types should be directly imported from
Vector = list[float]

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

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

Đã phản đối kể từ phiên bản 3.9: Các lớp

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
88 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
89 từ
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
90 hiện 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:
    ...
52. Xem PEP 585 và loại bí danh chung.Classes
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
88 and
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
89 from
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
90 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:
    ...
52. See PEP 585 and Generic Alias Type.

classtyping.text¶typing.Text

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
92 là bí danh cho
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34. Nó được cung cấp để cung cấp một đường dẫn tương thích phía trước cho mã Python 2: Trong Python 2,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
92 là một bí danh cho
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
95.

Sử dụng

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
92 để chỉ ra rằng giá trị phải chứa chuỗi Unicode theo cách tương thích với cả Python 2 và Python 3:

from collections.abc import Mapping, Sequence

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

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

Không dùng nữa vì phiên bản 3.11: Python 2 không còn được hỗ trợ và hầu hết các trình kiểm tra loại cũng không còn hỗ trợ kiểm tra loại mã Python 2. Việc loại bỏ bí danh hiện không được lên kế hoạch, nhưng người dùng được khuyến khích sử dụng

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34 thay vì
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
92 bất cứ khi nào có thể.Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34 instead of
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
92 wherever possible.

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
02 có thể được sử dụng để chú thích các đối số của bất kỳ loại nào được đề cập ở trên.

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

Phiên bản chung của

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

Vector = list[float]

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
20. Ví dụ:

Vector = list[float]

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

Nếu trình tạo của bạn chỉ mang lại các giá trị, hãy đặt

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

Vector = list[float]

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
03

classtyping.hashable¶ typing.Hashable

Một bí danh đến

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

classtyping.sized¶typing.Sized

Một bí danh đến

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
22, ví dụ:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
04

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
33. Ví dụ:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
05

Không giống như các trình tạo bình thường, các trình tạo async không thể trả về một giá trị, do đó không có tham số loại

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
99. Như với
from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

Nếu trình tạo của bạn chỉ mang lại các giá trị, hãy đặt

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
21 thành
Vector = list[float]

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

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

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
06

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

from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

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

Vector = list[float]

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

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
81.

classtyping.supportsabs¶typing.SupportsAbs

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

from typing import NewType

UserId = NewType('UserId', int)

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

classtyping.supportsbytes¶typing.SupportsBytes

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

from typing import NewType

UserId = NewType('UserId', int)

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

classtyping.supportscomplex¶ typing.SupportsComplex

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

from typing import NewType

UserId = NewType('UserId', int)

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

classtyping.supportsfloat¶ typing.SupportsFloat

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

from typing import NewType

UserId = NewType('UserId', int)

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

classtyping.supportsindex¶ typing.SupportsIndex

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

classtyping.supportsInt¶ typing.SupportsInt

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

from typing import NewType

UserId = NewType('UserId', int)

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

classtyping.supportsround¶ typing.SupportsRound

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

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

Điều này trả về giá trị không thay đổi. Đối với người kiểm tra loại này báo hiệu rằng giá trị trả về có loại được chỉ định, nhưng trong thời gian chạy, chúng tôi cố tình không kiểm tra bất cứ điều gì (chúng tôi muốn điều này càng nhanh càng tốt).

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
54, nó sẽ phát ra lỗi nếu giá trị không thuộc loại được chỉ định:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
08

Vào thời gian chạy, điều này trả về đối số đầu tiên không thay đổi mà không có tác dụng phụ.

Chức năng này rất hữu ích để đảm bảo loại kiểm tra loại hiểu về một tập lệnh phù hợp với ý định của nhà phát triển:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
09

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

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

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

Example:

Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
10

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
90 là
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
64 hoặc
Vector = list[float]

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

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34 và cả hai tùy chọn đều được bao gồm bởi các trường hợp trước đó. Nếu một trình kiểm tra loại thấy rằng một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

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

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

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
61 thuộc loại
from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
63 để vượt qua kiểm tra loại, loại được suy ra của đối số được truyền trong phải là loại dưới cùng,
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
65 và không có gì khác.

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

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

gõ.assert_never (arg, /) ¶reveal_type(obj, /)

Hỏi trình kiểm tra loại tĩnh để xác nhận rằng một dòng mã là không thể truy cập được.

Ở đây, các chú thích cho phép trình kiểm tra loại suy ra rằng trường hợp cuối cùng không bao giờ có thể thực thi, bởi vì

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
90 là
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
64 hoặc
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34 và cả hai tùy chọn đều được bao gồm bởi các trường hợp trước đó. Nếu một trình kiểm tra loại thấy rằng một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
58 có thể truy cập được, nó sẽ phát ra một lỗi. Ví dụ: nếu chú thích loại cho
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
90 thay vào đó là
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
60, trình kiểm tra loại sẽ phát ra một lỗi chỉ ra rằng
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
61 thuộc loại
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
62. Đối với một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
63 để vượt qua kiểm tra loại, loại được suy ra của đối số được truyền trong phải là loại dưới cùng,
from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
65 và không có gì khác.

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
11

Trong thời gian chạy, điều này ném một ngoại lệ khi được gọi.

gõ.reveal_type (obj, /) ¶

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
12

Tiết lộ loại tĩnh suy ra của một biểu thức.

Khi trình kiểm tra loại tĩnh bắt gặp một cuộc gọi đến chức năng này, nó sẽ phát ra một chẩn đoán với loại đối số. Ví dụ:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
13

Mới trong phiên bản 3.11.

gõ.assert_never (arg, /) ¶typing.dataclass_transform

Hỏi trình kiểm tra loại tĩnh để xác nhận rằng một dòng mã là không thể truy cập được.

Ở đây, các chú thích cho phép trình kiểm tra loại suy ra rằng trường hợp cuối cùng không bao giờ có thể thực thi, bởi vì

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
90 là
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
64 hoặc
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
34 và cả hai tùy chọn đều được bao gồm bởi các trường hợp trước đó. Nếu một trình kiểm tra loại thấy rằng một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
58 có thể truy cập được, nó sẽ phát ra một lỗi. Ví dụ: nếu chú thích loại cho
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
90 thay vào đó là
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
60, trình kiểm tra loại sẽ phát ra một lỗi chỉ ra rằng
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
61 thuộc loại
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
62. Đối với một cuộc gọi đến
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
63 để vượt qua kiểm tra loại, loại được suy ra của đối số được truyền trong phải là loại dưới cùng,
from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
65 và không có gì khác.

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
14

Trong thời gian chạy, điều này ném một ngoại lệ khi được gọi.

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
15

gõ.reveal_type (obj, /) ¶

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
16

Tiết lộ loại tĩnh suy ra của một biểu thức.

Khi trình kiểm tra loại tĩnh bắt gặp một cuộc gọi đến chức năng này, nó sẽ phát ra một chẩn đoán với loại đối số. Ví dụ:

Điều này có thể hữu ích khi bạn muốn gỡ lỗi cách người kiểm tra loại của bạn xử lý một đoạn mã cụ thể.

  • Hàm trả về đối số của nó không thay đổi, cho phép sử dụng nó trong một biểu thức:

  • Hầu hết các trình kiểm tra loại hỗ trợ

    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    65 ở bất cứ đâu, ngay cả khi tên không được nhập từ
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    36. Nhập tên từ
    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # passes type checking; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    36 cho phép mã của bạn chạy mà không có lỗi thời gian chạy và truyền đạt ý định rõ ràng hơn.

  • Khi chạy, chức năng này in loại thời gian chạy của đối số của nó thành stderr và trả về nó không thay đổi:

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    96 Chỉ định danh sách tĩnh các lớp hoặc chức năng được hỗ trợ mô tả các trường, tương tự như
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    97.

  • Các đối số từ khóa khác tùy ý được chấp nhận để cho phép các phần mở rộng trong tương lai có thể.

Trình kiểm tra loại nhận ra các đối số tùy chọn sau đây trên các nhà xác định trường:

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    77 cho biết liệu trường có nên được đưa vào phương pháp tổng hợp
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    73 hay không. Nếu không xác định,
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    77 mặc định là
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    81.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    02 cung cấp giá trị mặc định cho trường.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    03 cung cấp một cuộc gọi lại thời gian chạy trả về giá trị mặc định cho trường. Nếu cả
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    02 và
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    03 đều không được chỉ định, trường được giả định là không có giá trị mặc định và phải được cung cấp một giá trị khi lớp được khởi tạo.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    06 là bí danh cho
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    03.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    83 cho biết trường có nên được đánh dấu là chỉ từ khóa hay không. Nếu
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    81, trường sẽ chỉ dành cho từ khóa. Nếu
    # 'output' is of type 'int', not 'UserId'
    output = UserId(23413) + UserId(54341)
    
    16, nó sẽ không chỉ là từ khóa. Nếu không xác định, giá trị của tham số
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    83 trên đối tượng được trang trí bằng
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    68 sẽ được sử dụng hoặc nếu điều đó không được xác định, giá trị của
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    94 trên
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    68 sẽ được sử dụng.

  • from typing import NewType
    
    UserId = NewType('UserId', int)
    
    ProUserId = NewType('ProUserId', UserId)
    
    15 cung cấp một tên thay thế cho trường. Tên thay thế này được sử dụng trong phương pháp
    from typing import NewType
    
    UserId = NewType('UserId', int)
    
    # Fails at runtime and does not pass type checking
    class AdminUserId(UserId): pass
    
    73 tổng hợp.

Trong thời gian chạy, người trang trí này ghi lại các lập luận của nó trong thuộc tính

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
17 trên đối tượng được trang trí. Nó không có hiệu ứng thời gian chạy khác.

Xem PEP 681 để biết thêm chi tiết.PEP 681 for more details.

Mới trong phiên bản 3.11.

@Gõ.Overload¶typing.overload

Trình trang trí

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
18 cho phép mô tả các chức năng và phương pháp hỗ trợ nhiều kết hợp khác nhau của các loại đối số. Một loạt các định nghĩa được trang trí ____ 718 phải được theo sau bởi chính xác một định nghĩa không được trang trí 718 (cho cùng một hàm/phương thức). Các định nghĩa được trang trí ____ 718 chỉ vì lợi ích của trình kiểm tra loại, vì chúng sẽ bị ghi đè bởi định nghĩa không được trang trí 718, trong khi loại sau được sử dụng trong thời gian chạy nhưng nên bị bỏ qua bởi trình kiểm tra loại. Trong thời gian chạy, gọi trực tiếp chức năng được trang trí ____ 718 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
24. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được thể hiện bằng cách sử dụng một liên kết hoặc biến loại:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
17

Xem PEP 484 để biết thêm chi tiết và so sánh với các ngữ nghĩa đánh máy khác.PEP 484 for more details and comparison with other typing semantics.

Đã thay đổi trong phiên bản 3.11: Các chức năng quá tải hiện có thể được nội tâm khi chạy bằng cách sử dụng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
25.Overloaded functions can now be introspected at runtime using
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
25.

gõ.get_overloads (func) ¶get_overloads(func)

Trả về một chuỗi các định nghĩa được trang trí ____ 718 cho FUNC. Func là đối tượng chức năng để thực hiện chức năng quá tải. Ví dụ: với định nghĩa của

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
27 trong tài liệu cho
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
18,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
29 sẽ trả về một chuỗi ba đối tượng chức năng cho ba quá tải được xác định. Nếu được gọi trên một hàm không có quá tải,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
25 trả về một chuỗi trống.

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
25 có thể được sử dụng để hướng nội một chức năng quá tải trong thời gian chạy.

Mới trong phiên bản 3.11.

@Gõ.Overload¶clear_overloads()

Trình trang trí

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
18 cho phép mô tả các chức năng và phương pháp hỗ trợ nhiều kết hợp khác nhau của các loại đối số. Một loạt các định nghĩa được trang trí ____ 718 phải được theo sau bởi chính xác một định nghĩa không được trang trí 718 (cho cùng một hàm/phương thức). Các định nghĩa được trang trí ____ 718 chỉ vì lợi ích của trình kiểm tra loại, vì chúng sẽ bị ghi đè bởi định nghĩa không được trang trí 718, trong khi loại sau được sử dụng trong thời gian chạy nhưng nên bị bỏ qua bởi trình kiểm tra loại. Trong thời gian chạy, gọi trực tiếp chức năng được trang trí ____ 718 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
24. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được thể hiện bằng cách sử dụng một liên kết hoặc biến loại:

Mới trong phiên bản 3.11.

@Gõ.Overload¶typing.final

Trình trang trí

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
18 cho phép mô tả các chức năng và phương pháp hỗ trợ nhiều kết hợp khác nhau của các loại đối số. Một loạt các định nghĩa được trang trí ____ 718 phải được theo sau bởi chính xác một định nghĩa không được trang trí 718 (cho cùng một hàm/phương thức). Các định nghĩa được trang trí ____ 718 chỉ vì lợi ích của trình kiểm tra loại, vì chúng sẽ bị ghi đè bởi định nghĩa không được trang trí 718, trong khi loại sau được sử dụng trong thời gian chạy nhưng nên bị bỏ qua bởi trình kiểm tra loại. Trong thời gian chạy, gọi trực tiếp chức năng được trang trí ____ 718 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
24. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được thể hiện bằng cách sử dụng một liên kết hoặc biến loại:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
18

Xem PEP 484 để biết thêm chi tiết và so sánh với các ngữ nghĩa đánh máy khác.PEP 591 for more details.

Đã thay đổi trong phiên bản 3.11: Các chức năng quá tải hiện có thể được nội tâm khi chạy bằng cách sử dụng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
25.

gõ.get_overloads (func) ¶The decorator will now set the

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
32 attribute to
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
81 on the decorated object. Thus, a check like
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
34 can be used at runtime to determine whether an object
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
35 has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

Trả về một chuỗi các định nghĩa được trang trí ____ 718 cho FUNC. Func là đối tượng chức năng để thực hiện chức năng quá tải. Ví dụ: với định nghĩa của
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
27 trong tài liệu cho
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
18,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
29 sẽ trả về một chuỗi ba đối tượng chức năng cho ba quá tải được xác định. Nếu được gọi trên một hàm không có quá tải,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
25 trả về một chuỗi trống.
typing.no_type_check

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
25 có thể được sử dụng để hướng nội một chức năng quá tải trong thời gian chạy.

gõ.clear_overloads () ¶decorator. With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses).

Xóa tất cả các quá tải đã đăng ký trong sổ đăng ký nội bộ. Điều này có thể được sử dụng để đòi lại bộ nhớ được sử dụng bởi sổ đăng ký.

@Gõ.Final¶typing.no_type_check_decorator

Một người trang trí để chỉ ra để gõ các trình kiểm tra rằng phương pháp được trang trí không thể được ghi đè, và lớp được trang trí không thể được phân nhóm. Ví dụ:

Không có kiểm tra thời gian chạy của các thuộc tính này. Xem PEP 591 để biết thêm chi tiết.

Mới trong phiên bản 3.8.typing.type_check_only

Đã thay đổi trong phiên bản 3.11: Trình trang trí hiện sẽ đặt thuộc tính

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
32 thành
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
81 trên đối tượng được trang trí. Do đó, một kiểm tra như
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
34 có thể được sử dụng trong thời gian chạy để xác định xem một đối tượng
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
35 có được đánh dấu là cuối cùng hay không. Nếu đối tượng được trang trí không hỗ trợ các thuộc tính thiết lập, người trang trí trả về đối tượng không thay đổi mà không gây ra ngoại lệ.

@gõ.no_type_check¶

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
19

Trang trí để chỉ ra rằng chú thích không phải là gợi ý loại.

Người trợ giúp nội tâm

gõ.get_type_hints (obj, globalns = none, localns = none, wasing_extras = false) ¶get_type_hints(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. Đối với một lớp
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
25, 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:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
95 dọc theo
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
43 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)
44 bằng
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
98, trừ khi
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
46 được đặt thành
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
81 (xem
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
45 để biết thêm thông tin). Ví dụ:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
70 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)
46 như là một phần của PEP 593.Added
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
46 parameter as part of PEP 593.

Đã thay đổi trong phiên bản 3.11: Trước đây,

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
51 đã được thêm vào cho các chú thích chức năng và phương thức nếu giá trị mặc định bằng
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
61 đã được đặt. Bây giờ chú thích được trả lại không thay đổi.Previously,
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
51 was added for function and method annotations if a default value equal to
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
61 was set. Now the annotation is returned unchanged.

gõ.get_args (tp) ¶ gõ.get_origin (tp) ¶get_args(tp)typing.get_origin(tp)

Cung cấp nội tâm cơ bản cho các loại chung và các hình thức gõ đặc biệt.

Đối với một đối tượng gõ có dạng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
53, các chức năng này trả về
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
54 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
55. Nếu
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
54 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)
67, 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)
54 là một liên minh hoặc
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
41 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)
55 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)
61 do bộ nhớ đệm loại. Đối với các đối tượng không được hỗ trợ trả về
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
61 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
63 tương ứng. Ví dụ:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
21

Mới trong phiên bản 3.8.

gõ.is_typeddict (tp) ¶is_typeddict(tp)

Kiểm tra xem một loại là

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42.

Ví dụ:

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
22

Mới trong phiên bản 3.10.

classtyping.forwardref¶typing.ForwardRef

Một lớp được sử dụng để biểu diễn gõ nội bộ của các tham chiếu chuyển tiếp chuỗi. Ví dụ,

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
65 được chuyển đổi hoàn toàn thành
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
66. Lớp này không nên được người dùng khởi tạo, nhưng có thể được sử dụng bởi các công cụ hướng nội.

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
70 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)
67 will not be implicitly transformed into
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
68 and thus will not automatically resolve to
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
69.

Đã 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)
46 như là một phần của PEP 593.

Đã thay đổi trong phiên bản 3.11: Trước đây, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId) 51 đã được thêm vào cho các chú thích chức năng và phương thức nếu giá trị mặc định bằng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) 61 đã được đặt. Bây giờ chú thích được trả lại không thay đổi.

gõ.get_args (tp) ¶ gõ.get_origin (tp) ¶TYPE_CHECKING

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.

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
23

Đối với một đối tượng gõ có dạng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
53, các chức năng này trả về
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
54 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
55. Nếu
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
54 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)
67, 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)
54 là một liên minh hoặc
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
41 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)
55 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)
61 do bộ nhớ đệm loại. Đối với các đối tượng không được hỗ trợ trả về
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
61 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
63 tương ứng. Ví dụ:

Ghi chú

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
70 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)
46 như là một phần của PEP 593.

Đã thay đổi trong phiên bản 3.11: Trước đây, from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId) 51 đã được thêm vào cho các chú thích chức năng và phương thức nếu giá trị mặc định bằng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) 61 đã được đặt. Bây giờ chú thích được trả lại không thay đổi.

gõ.get_args (tp) ¶ gõ.get_origin (tp) ¶

Cung cấp nội tâm cơ bản cho các loại chung và các hình thức gõ đặc biệt.

Đối với một đối tượng gõ có dạng

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
53, các chức năng này trả về
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
54 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
55. Nếu
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
54 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)
67, 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)
54 là một liên minh hoặc
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
41 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)
55 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)
61 do bộ nhớ đệm loại. Đối với các đối tượng không được hỗ trợ trả về
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
61 và
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
63 tương ứng. Ví dụ:

Mới trong phiên bản 3.8.

PEP/issue

gõ.is_typeddict (tp) ¶

3.8

3.13

bpo-38291

Kiểm tra xem một loại là

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
42.

3.9

Ví dụ:

Mới trong phiên bản 3.10.

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
79

3.11

Ví dụ:

gh-92332

Là gõ cần thiết trong Python?

Python hỗ trợ khái niệm gõ dần dần.Điều đó có nghĩa là khi bạn đang viết mã của mình, bạn có thể giới thiệu các loại của mình khi bạn đi.02:57 Bất kỳ mã nào không có gợi ý loại sẽ bị bỏ qua bởi trình kiểm tra.Nó có ý nghĩa để thêm gợi ý loại vào các thành phần quan trọng trước.. What that means is that as you're writing your code, you can introduce your types as you go. 02:57 Any code without type hints will be ignored by the checker. It makes sense to add type hints to critical components first.

Điểm gõ vào Python là gì?

Được giới thiệu kể từ Python 3.5, mô -đun gõ của Python cố gắng cung cấp một cách gợi ý để giúp người kiểm tra loại tĩnh và linter dự đoán chính xác các lỗi.provide a way of hinting types to help static type checkers and linters accurately predict errors.

Việc gõ có làm cho Python nhanh hơn không?

Vì vậy, tóm lại: Không, chúng sẽ không gây ra bất kỳ hiệu ứng thời gian chạy nào, trừ khi bạn sử dụng chúng một cách rõ ràng.no, they will not cause any run-time effects, unless you explicitly make use of them.

Bạn có nên sử dụng gợi ý loại?

Gỡ lỗi dễ dàng hơn: Nếu bây giờ nó không rõ ràng.Sử dụng các gợi ý loại có thể giúp việc gỡ lỗi dễ dàng hơn nhiều trong mã của bạn và trong rất nhiều trường hợp có thể hoàn toàn tránh được một số lỗi, đặc biệt nếu được sử dụng với trình kiểm tra loại tĩnh như MyPy.Using type hints can make it much easier to debug issues in your code and in a lot of cases can completely avoid some errors, particularly if used with a static type checker like mypy.