Hướng dẫn python class optional arguments - đối số tùy chọn lớp python

You can set default parameters:

class OpticalTransition(object):
    def __init__(self, chemical, i, j=None, k=0):
        self.chemical = chemical
        self.i = i
        self.k = k
        self.j = j if j is not None else i

If you don't explicitly call the class with

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 and
def greeting(name: str) -> str:
    return 'Hello ' + name
00, your instance will use the defaults you defined in the init parameters. So when you create an instance of this object, you can use all four parameters as normal:
def greeting(name: str) -> str:
    return 'Hello ' + name
01

Or you can omit the parameters with defaults with

def greeting(name: str) -> str:
    return 'Hello ' + name
02, which would be interpreted as
def greeting(name: str) -> str:
    return 'Hello ' + name
03

You can use some default values but not all of them as well, by referencing the name of the parameter:

def greeting(name: str) -> str:
    return 'Hello ' + name
04 uses
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's default but not
def greeting(name: str) -> str:
    return 'Hello ' + name
00's.

Python won't allow you to do

def greeting(name: str) -> str:
    return 'Hello ' + name
07 as a default parameter (
def greeting(name: str) -> str:
    return 'Hello ' + name
08 isn't an existing object that the class definition can see), so the
def greeting(name: str) -> str:
    return 'Hello ' + name
09 line handles this with an
def greeting(name: str) -> str:
    return 'Hello ' + name
10 statement that in effect does the same thing.

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

Nội phân Chính showShow

  • Peps¶ có liên quan
  • Gõ bí danh
  • Các loại chung do người dùng xác định
  • Bất kỳ loại
  • Danh nghĩa so với phân nhóm cấu trúc
  • Nội dung mô -đun
  • Đặc biệt gõ nguyên thủy
  • Bộ sưu tập bê tông chung chung
  • Lớp học cơ sở trừu tượng Jo
  • Giao thức
  • Chức năng và Người trang trí
  • Người trợ giúp nội tâm

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

Ghi chú

Nếu

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
95 đượ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
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
80. Đ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.PEP 484. For a simplified introduction to type hints, see PEP 483.

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

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

Nội phân Chính show

Peps¶ có liên quan

Peps¶ có liên quan

Gõ bí danhPEP 484 and PEP 483, a number of PEPs have modified and enhanced Python’s framework for type annotations. These include:

  • Các loại chung do người dùng xác định: Syntax for Variable Annotations

    Bất kỳ loại

  • Danh nghĩa so với phân nhóm cấu trúc: Protocols: Structural subtyping (static duck typing)

    Nội dung mô -đun

  • Đặc biệt gõ nguyên thủy: Type Hinting Generics In Standard Collections

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

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

    Giao thức

  • Chức năng và Người trang trí: TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys

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

  • Mã nguồn: lib/gõ.py: Adding a final qualifier to typing

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

  • Mô -đun này cung cấp hỗ trợ thời gian chạy cho các gợi ý loại. Hỗ trợ cơ bản nhất bao gồm các loại
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    11,
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    12,
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    13,
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    14 và
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    15. Để 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.
    : Flexible function and variable annotations

    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
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    16, đối số
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    17 dự kiến ​​sẽ thuộc loại
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    18 và loại trả về
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    18. Các kiểu con được chấp nhận là đối số.
    : Allow writing union types as
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    30

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

    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    20. 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.union of types

  • 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:: Parameter Specification Variables

    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 định nghĩa hàm và
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    21
    : Explicit Type Aliases

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

  • Giới thiệu
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    22 và người trang trí
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    23
    : User-Defined Type Guards

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

Gõ bí danh

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

Vector = list[float]

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

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

Bất kỳ 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:
    ...

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

Nội dung mô -đun

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

from typing import NewType

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

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

Giao thức

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)

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.

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

def greeting(name: str) -> str:
    return 'Hello ' + name
56 sẽ làm cho trình kiểm tra loại tĩnh điều trị
def greeting(name: str) -> str:
    return 'Hello ' + name
57 là chính xác tương đương với
def greeting(name: str) -> str:
    return 'Hello ' + name
58 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,

def greeting(name: str) -> str:
    return 'Hello ' + name
41 tuyên bố một loại là một loại phụ của loại khác. Thực hiện
def greeting(name: str) -> str:
    return 'Hello ' + name
60 sẽ làm cho trình kiểm tra loại tĩnh xử lý
def greeting(name: str) -> str:
    return 'Hello ' + name
49 dưới dạng lớp con của
def greeting(name: str) -> str:
    return 'Hello ' + name
58, có nghĩa là giá trị của loại
def greeting(name: str) -> str:
    return 'Hello ' + name
58 không thể được sử dụng ở những nơi dự kiến ​​giá trị của loại
def greeting(name: str) -> str:
    return 'Hello ' + name
49. Đ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:

def greeting(name: str) -> str:
    return 'Hello ' + name
41 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
def greeting(name: str) -> str:
    return 'Hello ' + name
41 qua chức năng thông thường. Tuy nhiên, chi phí này sẽ được giảm trong 3.11.0.
def greeting(name: str) -> str:
    return 'Hello ' + name
41 is now a class rather than a function. There is some additional runtime cost when calling
def greeting(name: str) -> str:
    return 'Hello ' + name
41 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

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

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
33. 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ử
def greeting(name: str) -> str:
    return 'Hello ' + name
34 có thể được sử dụng. Họ lần lượt nhận dạng
def greeting(name: str) -> str:
    return 'Hello ' + name
71 và
def greeting(name: str) -> str:
    return 'Hello ' + name
72.

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.

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

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à

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

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

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.

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

def greeting(name: str) -> str:
    return 'Hello ' + name
74 Là một lớp cơ sở định nghĩa rằng lớp
def greeting(name: str) -> str:
    return 'Hello ' + name
75 lấy một tham số loại duy nhất
def greeting(name: str) -> str:
    return 'Hello ' + name
76. Điều này cũng làm cho
def greeting(name: str) -> str:
    return 'Hello ' + name
76 có giá trị như một loại trong cơ thể lớp.

Lớp cơ sở

def greeting(name: str) -> str:
    return 'Hello ' + name
15 xác định
def greeting(name: str) -> str:
    return 'Hello ' + name
79 để
def greeting(name: str) -> str:
    return 'Hello ' + name
80 hợp lệ dưới dạng loại:

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
14 đều được cho phép làm tham số cho một loại chung:

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
15 phải khác biệt. Điều này không hợp lệ:

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

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

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

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

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

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

Trong trường hợp này

def greeting(name: str) -> str:
    return 'Hello ' + name
84 có một tham số duy nhất,
def greeting(name: str) -> str:
    return 'Hello ' + name
76.

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

def greeting(name: str) -> str:
    return 'Hello ' + name
11 cho mỗi vị trí. Trong ví dụ sau,
def greeting(name: str) -> str:
    return 'Hello ' + name
87 không chung chung mà là kế thừa ngầm từ
def greeting(name: str) -> str:
    return 'Hello ' + name
88:

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

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
15 không còn có Metaclass tùy chỉnh.
def greeting(name: str) -> str:
    return 'Hello ' + name
15 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

def greeting(name: str) -> str:
    return 'Hello ' + name
90. 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
def greeting(name: str) -> str:
    return 'Hello ' + name
33:

Vector = list[float]

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
92 và cả
def greeting(name: str) -> str:
    return 'Hello ' + name
93 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:

Vector = list[float]

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
33 có thể không đúng
def greeting(name: str) -> str:
    return 'Hello ' + name
95 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:

def greeting(name: str) -> str:
    return 'Hello ' + name
15 hiện có thể được tham số hóa qua các biểu thức tham số. Xem
def greeting(name: str) -> str:
    return 'Hello ' + name
33 và PEP 612 để biết thêm chi tiết.
def greeting(name: str) -> str:
    return 'Hello ' + name
15 can now be parameterized over parameter expressions. See
def greeting(name: str) -> str:
    return 'Hello ' + name
33 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.

Bất kỳ loại

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

def greeting(name: str) -> str:
    return 'Hello ' + name
11. Một trình kiểm tra loại tĩnh sẽ coi mọi loại là tương thích với
def greeting(name: str) -> str:
    return 'Hello ' + name
11 và
def greeting(name: str) -> str:
    return 'Hello ' + name
11 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

def greeting(name: str) -> str:
    return 'Hello ' + name
11 và gán nó cho bất kỳ biến nào:

Vector = list[float]

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
11 cho một loại chính xác hơn. Ví dụ: Trình kiểm tra loại tĩnh đã không báo cáo lỗi khi gán
Vector = list[float]

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

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

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

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

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
04 đã được tuyên bố là loại
def greeting(name: str) -> str:
    return 'Hello ' + name
18 và nhận được giá trị
def greeting(name: str) -> str:
    return 'Hello ' + name
42 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

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

Vector = list[float]

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

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

Hành vi này cho phép

def greeting(name: str) -> str:
    return 'Hello ' + name
11 được sử dụng như một hatch thoát ra khi bạn cần trộn mã được gõ linh hoạt và thống kê.

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

def greeting(name: str) -> str:
    return 'Hello ' + name
11 với hành vi của
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
11. Tương tự như
def greeting(name: str) -> str:
    return 'Hello ' + name
11, mọi loại là một loại phụ của
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
11. Tuy nhiên, không giống như
def greeting(name: str) -> str:
    return 'Hello ' + name
11, điều ngược lại không đúng:
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
11 không phải là một kiểu con của mọi loại khác.

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

Vector = list[float]

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

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

Vector = list[float]

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

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

Sử dụng

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
11 để chỉ ra rằng một giá trị có thể là bất kỳ loại nào theo cách kiểu an toàn. Sử dụng
def greeting(name: str) -> str:
    return 'Hello ' + name
11 để 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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
19 được cho phép trong đó một lớp
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20 được mong đợi nếu và chỉ khi
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
19 là một lớp con của
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
20.PEP 484 defined the Python static type system as using nominal subtyping. This means that a class
Vector = list[float]

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

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

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

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

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

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

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

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

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ư

Vector = list[float]

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

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

Vector = list[float]

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

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

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

Vector = list[float]

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

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

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
24 to be implicitly considered a subtype of both
Vector = list[float]

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

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

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
26 by static type checkers. This is known as structural subtyping (or static duck-typing):

Vector = list[float]

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
22, 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

def greeting(name: str) -> str:
    return 'Hello ' + name
15 để hỗ trợ các biến loại bên trong
Vector = list[float]

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

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

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
20 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ợ

Vector = list[float]

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

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

________ 233 ________ 234¶

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

  • Mọi loại đều tương thích với

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

  • def greeting(name: str) -> str:
        return 'Hello ' + name
    
    11 tương thích với mọi loại.

________ 233 ________ 238¶

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

Vector = list[float]

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

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

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

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

________ 233 ________ 240¶

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

Vector = list[float]

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

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

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
29, mỗi loại có một cú pháp duy nhất.

________ 233 ________ 243¶

Loại tuple;

Vector = list[float]

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

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

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

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

Ví dụ:

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
46 là một bộ của hai yếu tố tương ứng với các biến loại T1 và T2.
Vector = list[float]

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

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
48. Một đơn vị
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 tương đương với
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
50, và lần lượt
Vector = list[float]

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

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

________ 233 ________ 253¶

Loại công đoàn;

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
54 tương đương với
def greeting(name: str) -> str:
    return 'Hello ' + name
30 và có nghĩa là X hoặc Y.

Để xác định một liên minh, hãy sử dụng, ví dụ:

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
56 hoặc tốc ký
Vector = list[float]

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

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

    Vector = list[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]
    
    # typechecks; a list of floats qualifies as a Vector.
    new_vector = scale(2.0, [1.0, -4.2, 5.4])
    
    9
  • Các công đoàn của một cuộc tranh luận duy nhất biến mất, ví dụ:

    from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message(message: str, servers: Sequence[Server]) -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message(
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
        ...
    
    0
  • Các đối số dự phòng được bỏ qua, 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:
        ...
    
    1
  • Khi so sánh các công đoàn, thứ tự đối số bị bỏ qua, 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:
        ...
    
    2
  • Bạn không thể phân lớp hoặc khởi tạo

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

  • Bạn không thể viết

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

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

________ 233 ________ 261¶

Loại tùy chọn.

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
62 tương đương với
Vector = list[float]

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

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

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

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

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
65 về chú thích loại của nó chỉ vì nó là tùy chọn. 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

Mặt khác, nếu giá trị rõ ràng của

def greeting(name: str) -> str:
    return 'Hello ' + name
39 được phép, việc sử dụng
Vector = list[float]

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

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

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
63. Xem biểu thức loại công đoàn.Optional can now be written as
Vector = list[float]

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

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

________ 233 ________ 270¶

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

Vector = list[float]

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
68 (Ellipsis theo nghĩa đen) có thể được sử dụng để gõ Gợi ý có thể gọi được lấy bất kỳ số lượng đối số nào và trả lại
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
73. Một đơn giản
def greeting(name: str) -> str:
    return 'Hello ' + name
13 tương đương với
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
75, và lần lượt
Vector = list[float]

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
33. 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ử
def greeting(name: str) -> str:
    return 'Hello ' + name
34 có thể được sử dụng. Họ lần lượt nhận dạng
def greeting(name: str) -> str:
    return 'Hello ' + name
71 và
def greeting(name: str) -> str:
    return 'Hello ' + name
72.

________ 233 ________ 282¶

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

def greeting(name: str) -> str:
    return 'Hello ' + name
13 và
def greeting(name: str) -> str:
    return 'Hello ' + name
33 để 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
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
85.
def greeting(name: str) -> str:
    return 'Hello ' + name
34 hiện chỉ hợp lệ khi được sử dụng làm đối số đầu tiên cho
def greeting(name: str) -> str:
    return 'Hello ' + name
13. Tham số cuối cùng của
def greeting(name: str) -> str:
    return 'Hello ' + name
34 phải là
def greeting(name: str) -> str:
    return 'Hello ' + name
33.

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
90 cung cấp một
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
91 cho chức năng được trang trí,
def greeting(name: str) -> str:
    return 'Hello ' + name
34 có thể được sử dụng để chỉ ra rằng
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
90 mong đợi một cuộc gọi có thể gọi được trong một
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
94 là đối số đầu tiên và trả về một dấu hiệu có thể gọi với một loại khác nhau. Trong trường hợp này,
def greeting(name: str) -> str:
    return 'Hello ' + name
33 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 collections.abc import Sequence

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

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

# The static type checker will treat the previous 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

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

    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    33 và
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    34).
    – Parameter Specification Variables (the PEP which introduced
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    33 and
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    34).

  • def greeting(name: str) -> str:
        return 'Hello ' + name
    
    33 và
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    13.

Lớp ________ 233 ________ 301 (chung [CT_CO]) ¶(Generic[CT_co])

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
02 có thể chấp nhận giá trị loại
from collections.abc import Sequence

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

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

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

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

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

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

from collections.abc import Sequence

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

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

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

Lưu ý rằng

from collections.abc import Sequence

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

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

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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

Thực tế là

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
04 là hiệp phương sai ngụ ý rằng tất cả các lớp con của
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
02 nên thực hiện cùng một chữ ký của hàm tạo và chữ ký phương pháp lớp là
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
02. Trình kiểm tra loại nên gắn cờ vi phạm này, nhưng cũng nên cho phép các cuộc gọi xây dựng trong các lớp con phù hợp với các cuộc gọi xây dựng trong lớp cơ sở được chỉ định. Làm thế nào trình kiểm tra loại được yêu cầu để xử lý trường hợp cụ thể này có thể thay đổi trong các sửa đổi trong tương lai của PEP 484.PEP 484.

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
10 là các lớp,
def greeting(name: str) -> str:
    return 'Hello ' + name
11, các biến loại và liên minh của bất kỳ loại nào trong số này. Ví dụ:type variables, and unions of any of these types. For example:

from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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:
    ...
12 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:
    ...
10, lần lượt 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:
    ...
14, là gốc của hệ thống phân cấp Metaclass Python.

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

________ 233 ________ 316¶

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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 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 collections.abc import Sequence

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

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

# The static type checker will treat the previous 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, 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:

def greeting(name: str) -> str:
    return 'Hello ' + name
25 hiện đã khử trùng các tham số. So sánh bình đẳng của các đối tượng
def greeting(name: str) -> str:
    return 'Hello ' + name
25 không còn phụ thuộc vào thứ tự. Các đối tượng
def greeting(name: str) -> str:
    return 'Hello ' + name
25 hiện sẽ tăng ngoại lệ
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
22 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.
def greeting(name: str) -> str:
    return 'Hello ' + name
25 now de-duplicates parameters. Equality comparisons of
def greeting(name: str) -> str:
    return 'Hello ' + name
25 objects are no longer order dependent.
def greeting(name: str) -> str:
    return 'Hello ' + name
25 objects will now raise 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:
    ...
22 exception during equality comparisons if one of their parameters are not hashable.

________ 233 ________ 324¶

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

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

from typing import NewType

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

def greeting(name: str) -> str:
    return 'Hello ' + name
21 chỉ chấp nhận các loại và không thể được đăng ký thêm.

def greeting(name: str) -> str:
    return 'Hello ' + name
21 không phải là một lớp và không nên được sử dụ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:
    ...
27 hoặc
from collections.abc import Sequence

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

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

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

from typing import NewType

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

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

________ 233 ________ 331¶

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

from typing import NewType

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

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

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

________ 233 ________ 333¶

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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), để trang trí các loại hiện có với siêu dữ liệu cụ thể theo ngữ cảnh (có thể là nhiều phần của nó, vì
def greeting(name: str) -> str:
    return 'Hello ' + name
29 là variadic). Cụ thể, loại
def greeting(name: str) -> str:
    return 'Hello ' + name
76 có thể được chú thích bằng siêu dữ liệ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:
    ...
37 thông qua TypeHint
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
38. Siêu dữ liệu này có thể được sử dụng để phân tích tĩnh hoặc trong thời gian chạy. Nếu một thư viện (hoặc công cụ) gặp phải một kiểu chữ
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
38 và không có logic đặc biệt cho siêu dữ liệ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:
    ...
37, nó sẽ bỏ qua nó và chỉ coi loại này là
def greeting(name: str) -> str:
    return 'Hello ' + name
76. Không giống như chức nă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:
    ...
42 hiện đang tồn tại trong mô -đun
def greeting(name: str) -> str:
    return 'Hello ' + name
20, vô hiệu hóa hoàn toàn các chú thích đánh máy trên một hàm hoặc một lớp, loại ____129 cho phép cả hai lần kiểm tra typic của
def greeting(name: str) -> str:
    return 'Hello ' + name
76 (có thể bỏ qua một cách an toà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:
    ...
37) .PEP 593 (
from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as
def greeting(name: str) -> str:
    return 'Hello ' + name
29 is variadic). Specifically, a type
def greeting(name: str) -> str:
    return 'Hello ' + name
76 can be annotated with metadata
from collections.abc import Sequence

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

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

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

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
38. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
38 and has no special logic for metadata
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
37, it should ignore it and simply treat the type as
def greeting(name: str) -> str:
    return 'Hello ' + name
76. Unlike the
from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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 functionality that currently exists in the
def greeting(name: str) -> str:
    return 'Hello ' + name
20 module which completely disables typechecking annotations on a function or a class, the
def greeting(name: str) -> str:
    return 'Hello ' + name
29 type allows for both static typechecking of
def greeting(name: str) -> str:
    return 'Hello ' + name
76 (which can safely ignore
from collections.abc import Sequence

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

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

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

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

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
29. Một công cụ hoặc thư viện gặp phải loại
def greeting(name: str) -> str:
    return 'Hello ' + name
29 có thể quét qua các chú thích để xác định xem chúng có được quan tâm không (ví dụ: sử dụng
from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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).

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

def greeting(name: str) -> str:
    return 'Hello ' + name
29 cho phép bạn đặt một số chú thích của cùng loại (hoặc khác nhau) trên bất kỳ nút nào, nên các công cụ hoặc thư viện tiêu thụ các chú thích đó chịu trách nhiệm đối phó với các bản sao tiềm năng. Ví dụ: nếu bạn đang thực hiện phân tích phạm vi giá trị, bạn có thể cho phép điều này:

from typing import NewType

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

Chuyể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:
    ...
52 đế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:
    ...
53 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

    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    29 phải là loại hợp lệ

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

    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    29 hỗ trợ các đối số variadic):

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    4
  • def greeting(name: str) -> str:
        return 'Hello ' + name
    
    29 phải được gọi với ít nhất hai đối 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:
        ...
    
    57 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:

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    5
  • Các loại

    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    29 đượ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:

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    6
  • Chú thích trùng lặp không được xóa:

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    7
  • def greeting(name: str) -> str:
        return 'Hello ' + name
    
    29 có thể được sử dụng với bí danh lồng nhau và chung chung:

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

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

________ 233 ________ 361¶

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.

def greeting(name: str) -> str:
    return 'Hello ' + name
36 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.

def greeting(name: str) -> str:
    return 'Hello ' + name
36 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:

from typing import NewType

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

Đô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 collections.abc import Sequence

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

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

# The static type checker will treat the previous 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 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 collections.abc import Sequence

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

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

# The static type checker will treat the previous 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ó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 collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message(message: str, servers: Sequence[Server]) -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message(
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
        ...
    
    66, loại đối số của nó là loại bên trong
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    36.

Ví dụ:

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

# typechecks
user_a = get_user_name(UserId(42351))

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

Nế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:
    ...
68 là phương thức lớp hoặc phiên bản, thì loại trong
def greeting(name: str) -> str:
    return 'Hello ' + name
36 bản đồ theo loại tham số thứ hai sau
from collections.abc import Sequence

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

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

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

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

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

# The static type checker will treat the previous 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.

Nói tóm lại, 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:
    ...
72, có nghĩa là nế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:
    ...
73 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:
    ...
66, thì
from collections.abc import Sequence

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

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

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

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:
    ...
77 không cần phải là một dạng hẹp hơn 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:
    ...
76 - 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 collections.abc import Sequence

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

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

# The static type checker will treat the previous 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 đến
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
81 mặc dù sau này không phải là một loại phụ của cái trước, 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:
    ...
82 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.

def greeting(name: str) -> str:
    return 'Hello ' + name
36 cũng hoạt động với các biến loại. Để biết thêm thông tin, hãy xem PEP 647 (Bộ bảo vệ loại do người dùng xác định).PEP 647 (User-Defined Type Guards).

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

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

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

Lớp ________ 233 ________ 385¶

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
2 Lớp ________ 233 ________ 387¶

Loại biến.

Usage:

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
15 để biết thêm thông tin về các loại chung. Chức năng chung hoạt động như sau:

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
14 chỉ có thể được giải quyết là chính xác là một trong những ràng buộc được đưa ra:

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
14 sẽ được giải quyết bằng cách sử dụng loại cụ thể nhất có thể:

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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:

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

# typechecks
user_a = get_user_name(UserId(42351))

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

Các biến loại ràng buộc đặc biệt hữu ích để chú thí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:
    ...
91 đóng vai trò là hàm tạo thay thế. Trong ví dụ sau (bởi Raymond Hettinger), biến loại
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
02 được liên kết với 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:
    ...
93 thông qua việc sử dụng tham chiếu chuyển tiếp. Sử dụng biến loại này để chú thích lớp
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
94, thay vì mã hóa loại trả về loại 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:
    ...
93, có nghĩa là trình kiểm tra loại có thể suy ra chính xác loại trả về ngay cả khi phương thức được gọi trên lớp con:

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

# typechecks
user_a = get_user_name(UserId(42351))

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

Trong thời gian chạ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:
    ...
96 sẽ tă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:
    ...
22. Nói chung,
from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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 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:
    ...
28 không nên được sử dụng với các loại.

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

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
01. Xem PEP 484 để biết thêm chi tiết. Theo mặc định, các biến loại là bất biến.PEP 484 for more details. By default, type variables are invariant.

Lớp ________ 233 ________ 403 (tên, *, ràng buộc = none, covariant = false(name, *, bound=None, covariant=False, contravariant=False)

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

from typing import NewType

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

Usage:

Các biến đặc tả tham số tồn tại chủ yếu vì lợi ích của bộ kiểm tra loại tĩnh. Chúng được sử dụng để chuyển tiếp các loại tham số của một người có thể gọi cho một người khác có thể gọi - một mẫu thường được tìm thấy trong các chức năng và bộ trang trí bậc cao. Chúng chỉ hợp lệ khi được sử dụng trong

def greeting(name: str) -> str:
    return 'Hello ' + name
34 hoặc là đối số đầu tiên cho
def greeting(name: str) -> str:
    return 'Hello ' + name
13 hoặc làm tham số cho thuốc generic do người dùng xác định. Xem
def greeting(name: str) -> str:
    return 'Hello ' + name
15 để biết thêm thông tin về các loại chung.

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

from typing import NewType

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

Không có

def greeting(name: str) -> str:
    return 'Hello ' + name
33, cách đơn giản nhất để chú thích điều này trước đây là sử dụng
def greeting(name: str) -> str:
    return 'Hello ' + name
14 với ràng buộc
Vector = list[float]

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

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

  1. Trình kiểm tra loại có thể loại kiểm tra chức năng

    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    12 vì
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    13 và
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    14 phải được gõ
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    11.

  2. from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    16 có thể được yêu cầu trong phần thân của bộ trang trí
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    08 khi trả lại hàm
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    12 hoặc trình kiểm tra loại tĩnh phải được yêu cầu bỏ qua
    from typing import NewType
    
    UserId = NewType('UserId', int)
    some_id = UserId(524313)
    
    19.

________ 420¶ ________ 421¶

def greeting(name: str) -> str:
    return 'Hello ' + name
33 nắm bắt cả các tham số vị trí và từ khóa,
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
24 có thể được sử dụng để chia
def greeting(name: str) -> str:
    return 'Hello ' + name
33 thành các thành phần của nó.
from typing import NewType

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

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

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

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

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
24 tương ứng là các trường hợp của
from typing import NewType

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

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

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

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
01 có thể được sử dụng để khai báo các loại chung hiệp phương sai hoặc contravariant. Đối số
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
36 cũng được chấp nhận, tương tự như
def greeting(name: str) -> str:
    return 'Hello ' + name
14. Tuy nhiên, ngữ nghĩa thực tế của các từ khóa này vẫn chưa được quyết định.

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

Ghi chú

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

Xem thêm

  • PEP 612 - Các biến đặc tả tham số (PEP đã giới thiệu

    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    33 và
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    34).
    – Parameter Specification Variables (the PEP which introduced
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    33 and
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    34).

  • def greeting(name: str) -> str:
        return 'Hello ' + name
    
    13 và
    def greeting(name: str) -> str:
        return 'Hello ' + name
    
    34.

________ 233 ________ 443¶ ________ 233 ________ 445¶

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

def greeting(name: str) -> str:
    return 'Hello ' + name
33. Thuộc tính
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
23 của
def greeting(name: str) -> str:
    return 'Hello ' + name
33 là một ví dụ là
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
24 là một ví dụ của
from typing import NewType

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
52 trên một trong hai đối tượng này sẽ trả về bản gốc
def greeting(name: str) -> str:
    return 'Hello ' + name
33:

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

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

Ghi chú

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

Xem thêm

PEP 612 - Các biến đặc tả tham số (PEP đã giới thiệu
def greeting(name: str) -> str:
    return 'Hello ' + name
33 và
def greeting(name: str) -> str:
    return 'Hello ' + name
34).(Generic)

def greeting(name: str) -> str:
    return 'Hello ' + name
13 và
def greeting(name: str) -> str:
    return 'Hello ' + name
34.

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

________ 233 ________ 443¶ ________ 233 ________ 445¶

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
33. Thuộc tính
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
23 của
def greeting(name: str) -> str:
    return 'Hello ' + name
33 là một ví dụ là
from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
24 là một ví dụ của
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
33. 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.PEP 544 for details. Protocol classes decorated with
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
61 (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.

Gọi

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
52 trên một trong hai đối tượng này sẽ trả về bản gốc
def greeting(name: str) -> str:
    return 'Hello ' + name
33:

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

________ 233 ________ 455¶

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
56 là
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
57 được định nghĩa là
from typing import NewType

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

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
1 Lớp ________ 233 ________ 460 (chung) ¶

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

Ghi chú

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:

________ 233 ________ 455¶

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
56 là
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
57 được định nghĩa là
from typing import NewType

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

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
1 Lớp ________ 233 ________ 460 (chung) ¶

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:

Usage:

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
61 (đượ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.

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

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

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

________ 462 ________ 233 ________ 464¶

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

Một giao thức như vậy có thể được sử dụ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:
    ...
27 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:
    ...
28. Điều này tă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:
    ...
22 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
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
68, chẳng hạn như
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
23. Ví dụ:Added support for PEP 526 variable annotation syntax.

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
71 là một lớp, do đó nó vượt qua kiểm tra
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
28 đối với
def greeting(name: str) -> str:
    return 'Hello ' + name
13. Tuy nhiên, phương pháp
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
74 chỉ tồn tại để tă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:
    ...
22 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)
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
71.Added support for default values, methods, and docstrings.

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

from typing import NewType

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
80 attributes are now regular dictionaries instead of instances of
from typing import NewType

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

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.Removed the

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
85 attribute in favor of the more standard
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
80 attribute which has the same information.

Lớp ________ 233 ________ 478¶(name, tp)

Phiên bản gõ của

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
79.NewType. At runtime it returns an object that returns its argument when called. Usage:

from typing import NewType

UserId = NewType('UserId', int)

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
41 is now a class rather than a function.

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.(dict)

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

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
80 đưa ra một dictor bản đồ tên trường thành các loại trường. .

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

from typing import NewType

UserId = NewType('UserId', int)

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

Sử dụng tương thích ngược:PEP 526,

def greeting(name: str) -> str:
    return 'Hello ' + name
26 supports two additional equivalent syntactic forms:

from typing import NewType

UserId = NewType('UserId', int)

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

Đã thay đổi trong phiên bản 3.6: Đã thêm hỗ trợ cho cú pháp chú thích biến PEP 526.identifiers, for example because they are keywords or contain hyphens. Example:

from typing import NewType

UserId = NewType('UserId', int)

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

Theo mặc định, tất cả các khóa phải có mặt trong

def greeting(name: str) -> str:
    return 'Hello ' + name
26. Có thể ghi đè lên điều này bằng cách chỉ định toàn bộ. Cách sử dụng:

from typing import NewType

UserId = NewType('UserId', int)

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

Điều này có nghĩa là một

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
99
def greeting(name: str) -> str:
    return 'Hello ' + name
26 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
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
01 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:
    ...
66 theo nghĩa đen là giá trị của đối số
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
03.
from collections.abc import Sequence

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

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
26 để kế thừa từ một hoặc nhiều loại
def greeting(name: str) -> str:
    return 'Hello ' + name
26 khác bằng cách sử dụng cú pháp dựa trên lớp. Cách sử dụng:

from typing import NewType

UserId = NewType('UserId', int)

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

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
07 có ba mụ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:
    ...
37,
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
10. Nó tương đương với định nghĩa này:

from typing import NewType

UserId = NewType('UserId', int)

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

Một

def greeting(name: str) -> str:
    return 'Hello ' + name
26 không thể kế thừa từ một lớp không phải là -____ 126, đáng chú ý bao gồm
def greeting(name: str) -> str:
    return 'Hello ' + name
15. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

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

A

def greeting(name: str) -> str:
    return 'Hello ' + name
26 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),
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
17.Annotations Best Practices for more information on annotations best practices),
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

________ 518¶

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
19 cho giá trị của đối số
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

________ 522¶

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
25 Các đối tượng có chứa các khóa cần thiết và không yêu cầu, tương ứng. Hiện tại, cách duy nhất để khai báo cả các khóa yêu cầu và không yêu cầu trong cùng một
def greeting(name: str) -> str:
    return 'Hello ' + name
26 là kế thừa hỗn hợp, khai báo
def greeting(name: str) -> str:
    return 'Hello ' + name
26 với một giá trị cho đối số
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
03 và sau đó kế thừa nó từ một
def greeting(name: str) -> str:
    return 'Hello ' + name
26 khác với giá trị khác với
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
0

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

________ 522¶PEP 589 for more examples and detailed rules of using

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
25 Các đối tượng có chứa các khóa cần thiết và không yêu cầu, tương ứng. Hiện tại, cách duy nhất để khai báo cả các khóa yêu cầu và không yêu cầu trong cùng một
def greeting(name: str) -> str:
    return 'Hello ' + name
26 là kế thừa hỗn hợp, khai báo
def greeting(name: str) -> str:
    return 'Hello ' + name
26 với một giá trị cho đối số
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
03 và sau đó kế thừa nó từ một
def greeting(name: str) -> str:
    return 'Hello ' + name
26 khác với giá trị khác với
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

Xem PEP 589 để biết thêm ví dụ và quy tắc chi tiết sử dụng def greeting(name: str) -> str: return 'Hello ' + name 26.

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

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

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

Lớp ________ 233 ________ 533 (Dict, Mutablemapping [KT, VT]) ¶

Một phiên bản chung của
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
95. 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ư
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
35.(list, MutableSequence[T])

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
1 Lớp ________ 233 ________ 537 (Danh sách, Mutablesequence [T]) ¶

Phiên bản chung của
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
38. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nó được ưu tiên sử dụng một loại bộ sưu tập trừu tượng, chẳng hạn như
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

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

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
2 Lớp ________ 233 ________ 542 (Set, Mutableset [T]) ¶(frozenset, AbstractSet[T_co])

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

Lớp ________ 233 ________ 546 (Frozenset, Abstractset [T_CO]) ¶

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

Ghi chú

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
49 là một hình thức đặc biệt.(collections.defaultdict, MutableMapping[KT, VT])

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

Lớp ________ 233 ________ 551 (Collections.Defaultdict, Mutablemapping [KT, VT]) ¶

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
52.(collections.OrderedDict, MutableMapping[KT, VT])

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

Lớp ________ 233 ________ 554 (Bộ sưu tập

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
55.(collections.ChainMap, MutableMapping[KT, VT])

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

Lớp ________ 233 ________ 557 (Bộ sưu tập.ChainMap, Mutablemapping [KT, VT]) ¶

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

Lớp ________ 233 ________ 557 (Bộ sưu tập.ChainMap, Mutablemapping [KT, VT]) ¶

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

Lớp ________ 233 ________ 557 (Bộ sưu tập.ChainMap, Mutablemapping [KT, VT]) ¶

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

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

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
75 namespace is deprecated and will be removed. These types should be directly imported from
def greeting(name: str) -> str:
    return 'Hello ' + name
20 instead.

Lớp ________ 233 ________ 563 (Deque, Mutablesequence [T]) ¶

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

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
88 namespace is deprecated and will be removed. These types should be directly imported from
def greeting(name: str) -> str:
    return 'Hello ' + name
20 instead.

Lớp ________ 233 ________ 566¶ Lớp ________ 233 ________ 568¶ Lớp ________ 233 ________ 570¶Classes

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

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

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
29. See PEP 585 and Generic Alias Type.

Loại chung
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
71 và các lớp con của nó
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
73 đại diện cho các loại luồng I/O như được trả về bởi
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

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

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

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
75 được không dùng nữa và sẽ bị xóa. Thay vào đó, các loại này nên được nhập trực tiếp từ
def greeting(name: str) -> str:
    return 'Hello ' + name
20.

Sử dụng

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

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
96 để 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 typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
3

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

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

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

Lớp ________ 233 ________ 603 (có kích thước, thu thập [T_CO]) ¶(Sized, Collection[T_co])

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

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

Lớp ________ 233 ________ 606 (trình tự [int]) ¶(Sequence[int])

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

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

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
08,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
09 và
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
10 của các chuỗi byte.

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

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

Lớp ________ 233 ________ 613 (có kích thước, có thể điều chỉnh được [T_CO], container [T_CO]) ¶(Sized, Iterable[T_co], Container[T_co])

Phiên bản chung của

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

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

Lớp ________ 233 ________ 616 (chung [T_CO]) ¶(Generic[T_co])

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

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

Lớp ________ 233 ________ 619 (Bản đồ,(MappingView, Generic[KT_co, VT_co])

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

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

Lớp ________ 233 ________ 622 (Bản đồview [KT_CO], Tóm tắt [KT_CO]) ¶(MappingView[KT_co], AbstractSet[KT_co])

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

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

Lớp ________ 233 ________ 625 (có kích thước, bộ sưu tập [kt], chung [vt_co]) ¶(Sized, Collection[KT], Generic[VT_co])

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
26. Loại này có thể được sử dụng như sau:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
4 Lớp ________ 233 ________ 628 (có kích thước, có thể điều chỉnh được [T_CO]) ¶(Sized, Iterable[T_co])

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

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

Lớp ________ 233 ________ 631 (ánh xạ [kt, vt]) ¶(Mapping[KT, VT])

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

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

Lớp ________ 233 ________ 634 (Chuỗi [T])(Sequence[T])

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

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

Lớp ________ 233 ________ 637 (Tóm tắt [T]) ¶(AbstractSet[T])

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

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

Lớp ________ 233 ________ 640 (có thể đảo ngược [T_CO], Bộ sưu tập [T_CO]) ¶(Reversible[T_co], Collection[T_co])

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

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

Lớp ________ 233 ________ 643 (Bản đồView [VT_CO]) ¶(MappingView[VT_co])

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

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

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

Lớp ________ 233 ________ 647 (chung [T_CO]) ¶(Generic[T_co])

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

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

Lớp ________ 233 ________ 650 (Itable [T_CO]) ¶(Iterable[T_co])

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

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

Lớp ________ 233 ________ 653 (iterator [t_co], chung [t_co, t_contra, v_co]) ¶(Iterator[T_co], Generic[T_co, T_contra, V_co])

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
54. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
5

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
55 của
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
56 hành xử trái ngược, không bất biến hoặc bất biến.

Nếu trình tạo của bạn sẽ chỉ mang lại các giá trị, hãy đặt

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
55 và
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
73 thành
def greeting(name: str) -> str:
    return 'Hello ' + name
39:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
6

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
60 hoặc
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
61:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
7 Lớp ________ 233 ________ 663¶

Một bí danh đến

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

Lớp ________ 233 ________ 666 (Itable [T_CO]) ¶(Iterable[T_co])

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

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

Lớp ________ 233 ________ 669¶

Một bí danh đến

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

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

Lớp ________ 233 ________ 672 (có thể chờ đợi [V_CO], chung [T_CO, T_Contra, V_CO])(Awaitable[V_co], Generic[T_co, T_contra, V_co])

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
73. 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
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
56, ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
8

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

Lớp ________ 233 ________ 676 (Asynciterator [T_CO], Generic [T_CO, T_Contra]) ¶(AsyncIterator[T_co], Generic[T_co, T_contra])

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
77. Ví dụ:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
9

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
73. Như với
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
56,
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
55 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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
55 thành
def greeting(name: str) -> str:
    return 'Hello ' + name
39:

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

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

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
83 hoặc
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
84:

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

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

Lớp ________ 233 ________ 686 (chung [T_CO]) ¶(Generic[T_co])

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

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

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

Lớp ________ 233 ________ 689 (không đồng bộ [T_CO]) ¶(AsyncIterable[T_co])

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

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

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

Lớp ________ 233 ________ 692 (chung [T_CO]) ¶(Generic[T_co])

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

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

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

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

Lớp ________ 233 ________ 695 (chung [T_CO]) ¶(Generic[T_co])

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

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

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

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

Lớp ________ 233 ________ 616 (chung [T_CO]) ¶(Generic[T_co])

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

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

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

Lớp ________ 233 ________ 698 (chung [T_CO]) ¶

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

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

from typing import NewType

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

Lớp ________ 233 ________ 702¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

Lớp ________ 233 ________ 705¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

Lớp ________ 233 ________ 708¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

Lớp ________ 233 ________ 711¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

Lớp ________ 233 ________ 714¶

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

UserId = NewType('UserId', int)

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

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

Lớp ________ 233 ________ 717¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

________ 233 ________ 723 (typ, val) ¶(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).

________ 462 ________ 233 ________ 726¶

Trình trang trí

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
27 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í ____ 727 phải được theo sau bởi chính xác một định nghĩa không được trang trí 727 (cho cùng một hàm/phương thức). Các định nghĩa được trang trí ____ 727 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í 727, 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í ____ 727 sẽ tăng
from typing import NewType

UserId = NewType('UserId', int)

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

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

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

________ 462 ________ 233 ________ 736¶

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

from collections.abc import 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

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.

________ 462 ________ 233 ________ 739¶

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

Điều này hoạt động như là người trang trí đẳng cấp hoặc chức năng. Với một lớp, nó áp dụng đệ quy cho tất cả các phương thức được xác định trong lớp đó (nhưng không phải là các phương thức được xác định trong các lớp học hoặc lớp con của nó).decorator. With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses).

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

________ 462 ________ 233 ________ 742¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

________ 462 ________ 233 ________ 747¶

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

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

from collections.abc import Callable

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

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

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

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

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

________ 233 ________ 749 (obj, globalns = none, localns = none(obj, globalns=None, localns=None, include_extras=False)

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

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
52. Nếu cần thiết,
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
53 đượ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
def greeting(name: str) -> str:
    return 'Hello ' + name
39 được đặt. Đối với một lớp
from collections.abc import Sequence

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

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

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

UserId = NewType('UserId', int)
some_id = UserId(524313)
80 dọc theo
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
57 theo thứ tự ngược lại.

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

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
58 bằng
def greeting(name: str) -> str:
    return 'Hello ' + name
76, trừ khi
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
60 được đặt thà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:
    ...
66 (xem
def greeting(name: str) -> str:
    return 'Hello ' + name
29 để biết thêm thông tin). 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
5

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

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
60 như là một phần của PEP 593.Added
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
60 parameter as part of PEP 593.

________ 233 ________ 766 (TP) ____ ____ 233 ________ 768 (TP) ¶(tp)
Vector = list[float]

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

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

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
68(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)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
69, các chức năng này trả về
from typing import NewType

UserId = NewType('UserId', int)

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

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
71. Nếu
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
70 là bí danh chung cho lớp tích hợp hoặc
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
49, thì nó sẽ được chuẩn hóa thành lớp ban đầu. Nếu
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
70 là một liên minh hoặc
def greeting(name: str) -> str:
    return 'Hello ' + name
25 có trong một loại chung khác, thì thứ tự của
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
71 có thể khác với thứ tự của các đối số gốc
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
77 do bộ nhớ đệm loại. Đối với các đối tượng không được hỗ trợ trả về
def greeting(name: str) -> str:
    return 'Hello ' + name
39 và
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
79 tương ứng. 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
6

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

________ 462 ________ 233 ________ 739¶(tp)

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

Điều này hoạt động như là người trang trí đẳng cấp hoặc chức năng. Với một lớp, nó áp dụng đệ quy cho tất cả các phương thức được xác định trong lớp đó (nhưng không phải là các phương thức được xác định trong các lớp học hoặc lớp con của nó).

from collections.abc import 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

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

________ 462 ________ 233 ________ 742¶

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

from typing import NewType

UserId = NewType('UserId', int)

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

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

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
87 will not be implicitly transformed into
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
88 and thus will not automatically resolve to
from typing import NewType

UserId = NewType('UserId', int)

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

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

Không thay đổi¶

________ 233 ________ 791¶

Một hằng số đặc biệt được giả định 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:
    ...
66 bởi các trình kiểm tra loại tĩnh của bên thứ 3.Đó là
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
01 khi chạy.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
8

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)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
94 từ thời gian chạy của trình thông dịch.Loại chú thích cho các biến cục bộ không được đánh giá, vì vậy chú thích thứ hai không cần phải được đặt trong các trích dẫn.

Ghi chú

Nếu

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
95 đượ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
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
80.Điều này làm cho việc sử dụng các trích dẫn xung quanh chú thích không cần thiết (xem PEP 563).PEP 563).

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