Phiên bản Python 3.8 không cho phép viết kiểu kết hợp là X |

Tôi là nhà nghiên cứu và phát triển web tự do đến từ Malawi. Tôi thích học những điều mới và việc viết lách giúp tôi hiểu và củng cố các khái niệm. Tôi hy vọng bằng cách chia sẻ kinh nghiệm của mình, những người khác có thể học được điều gì đó từ họ

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, linters, v.v.

Mô-đun này cung cấp hỗ trợ thời gian chạy cho các gợi ý loại như được chỉ định bởi PEP 484, PEP 526, PEP 544, PEP 586, PEP 589 và PEP 591. Hỗ trợ cơ bản nhất bao gồm các loại , , , , và. Để biết thông số kỹ thuật đầy đủ, vui lòng xem PEP 484. Để biết phần giới thiệu đơn giản về cách nhập gợi ý, hãy xem PEP 483

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

def greeting[name: str] -> str:
    return 'Hello ' + name

Trong hàm

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
5, đối số
from collections.abc import Callable

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

def async_query[on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]] -> None:
    # Body
6 được mong đợi là kiểu và kiểu trả về. Các kiểu con được chấp nhận làm đối số

Nhập bí danh

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

from collections.abc import Callable

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

def async_query[on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]] -> None:
    # Body
9 và
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
0 sẽ được coi là từ đồng nghĩa có thể hoán đổi cho nhau

Vector = list[float]

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

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

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

from collections.abc import Sequence

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

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

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

Lưu ý rằng

from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
1 dưới dạng gợi ý loại là trường hợp đặc biệt và được thay thế bằng
from collections.abc import Mapping, Sequence

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

Loại mới

Sử dụng hàm trợ giúp để tạo các loại riêng biệt

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]

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

def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

# does not typecheck; an int is not a UserId
user_b = get_user_name[-1]

Bạn vẫn có thể thực hiện tất cả các thao tác

from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
4 trên một biến loại
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
5, nhưng kết quả sẽ luôn là loại
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
4. Điều này cho phép bạn chuyển vào một
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
5 bất cứ nơi nào có thể có một
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
4, nhưng sẽ ngăn bạn vô tình tạo một
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
5 theo cách không hợp lệ

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]

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

Vector = list[float]

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

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

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
01 thành một hàm trả về ngay lập tức bất kỳ tham số nào bạn truyền vào nó. Điều đó có nghĩa là biểu thức
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
02 không tạo một lớp mới hoặc giới thiệu bất kỳ chi phí hoạt động nào ngoài cuộc gọi hàm thông thường

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
03 luôn đúng trong thời gian chạy

Điều này cũng có nghĩa là không thể tạo kiểu 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]]
01 vì đây là hàm nhận dạng trong thời gian chạy, không phải kiểu thực

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass

Tuy nhiên, có thể tạo dựa trên một 'có nguồn gố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]]
06

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]

và kiểm tra đánh máy cho

Vector = list[float]

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

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

Xem PEP 484 để biết thêm chi tiết

Ghi chú

Nhớ lại rằng việc sử dụng bí danh kiểu khai báo hai kiểu tương đương với nhau. Việc thực hiện

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
08 sẽ khiến trình kiểm tra loại tĩnh coi
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
09 là hoàn toàn 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]]
10 trong mọi trường hợp. Điều này hữu ích khi bạn muốn đơn giản hóa chữ ký loại phức tạp

Ngược lại,

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
06 tuyên bố một kiểu là kiểu con của kiểu khác. Việc thực hiện
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
12 sẽ khiến trình kiểm tra loại tĩnh coi
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
01 là một phân lớp 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]]
10, có nghĩa là giá trị của loại
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
10 không thể được sử dụng ở những nơi mà giá trị của loại
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
01 được mong đợi. Điều này hữu ích khi bạn muốn ngăn ngừa các lỗi logic với chi phí thời gian chạy tối thiểu

Có thể gọi

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

Vector = list[float]

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

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

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

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

Vector = list[float]

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

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

thuốc gốc

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

from collections.abc import Mapping, Sequence

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

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

Vector = list[float]

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

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

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

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

Vector = list[float]

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

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

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
20 như một lớp cơ sở định nghĩa rằng lớp
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
21 nhận một tham số loại duy nhất
Vector = list[float]

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

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

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
22 hợp lệ như một kiểu trong thân lớp

Lớp cơ sở định nghĩa sao 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]]
26 có giá trị như một loại

Vector = list[float]

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

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

Một loại chung có thể có bất kỳ số lượng biến loại nào và các biến loại có thể bị hạn 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]]
3

Mỗi đối số biến loại phải khác biệt. Điều này là không hợp lệ

Vector = list[float]

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

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

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

Vector = list[float]

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

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

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

Vector = list[float]

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

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

Trong trường hợp này,

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
29 có một tham số duy nhất,
Vector = list[float]

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

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

Sử dụng một lớp chung mà không chỉ định tham số loại giả định cho từng vị trí. Trong ví dụ sau,

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
32 không phải là chung chung nhưng hoàn toàn kế thừa 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]]
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]]
7

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

Vector = list[float]

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

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

Thay đổi trong phiên bản 3. 7. không còn có siêu dữ liệu tùy chỉnh

Lớp chung do người dùng định nghĩa có thể có ABC làm lớp cơ sở mà không có xung đột siêu dữ liệu. Siêu dữ liệu chung không được hỗ trợ. Kết quả của việc tham số hóa các khái quát được lưu vào bộ đệm và hầu hết các loại trong mô-đun gõ đều có thể băm và có thể so sánh bằng nhau

Loại bất kỳ

Một loại đặc biệt của loại là. Trình kiểm tra loại tĩnh sẽ coi mọi loại là tương thích với và tương thích với mọi loại

Điều này có nghĩa là có thể thực hiện bất kỳ thao tác hoặc lệnh gọi phương thức nào trên một giá trị kiểu và gán nó cho bất kỳ biến nào

Vector = list[float]

def scale[scalar: float, vector: Vector] -> Vector:
    return [scalar * num 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

Lưu ý rằng không có thao tác kiểm tra đánh máy nào được thực hiện khi gán giá trị của loại cho loại chính xác hơn. Ví dụ: trình kiểm tra kiểu tĩnh không báo lỗi khi gán

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
40 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]]
41 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]]
41 được khai báo là kiểu và nhận giá trị khi chạy

Hơn nữa, tất cả các hàm không có kiểu trả về hoặc kiểu tham số sẽ mặc định sử dụng

from collections.abc import Sequence

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

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

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

Hành vi này cho phép được sử dụng như một lối thoát hiểm khi bạn cần kết hợp mã được nhập động và tĩnh

Đối chiếu hành vi của với hành vi của. Tương tự như , mỗi loại là một kiểu con của. Tuy nhiên, không giống như , điều ngược lại là không đúng. không phải là một kiểu con của mọi kiểu khác

Điều đó có nghĩa là khi loại của một giá trị là , trình kiểm tra loại sẽ từ chối hầu hết mọi hoạt động trên nó và gán nó cho một biến [hoặc sử dụng nó làm giá trị trả về] của một loại chuyên biệt hơn là lỗi loại. Ví dụ

from collections.abc import Sequence

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

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

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

Sử dụng để chỉ ra rằng một giá trị có thể là bất kỳ loại nào theo cách an toàn. Sử dụng để chỉ ra rằng một giá trị được nhập động

Phân nhóm danh nghĩa và cấu trúc

Ban đầu, PEP 484 đã định nghĩa hệ thống kiểu tĩnh Python là sử dụng kiểu con danh nghĩa. Điều này có nghĩa là 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]]
56 được cho phép khi 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]]
57 được mong đợi nếu và chỉ khi 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]]
56 là lớp con của 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]]
57

Yêu cầu này trước đây cũng được áp dụng cho các lớp cơ sở trừu tượng, chẳng hạn như. Vấn đề với cách tiếp cận này là một lớp phải được đánh dấu rõ ràng để hỗ trợ chúng, điều này không phổ biến và không giống như những gì người ta thường làm trong mã Python được gõ động thành ngữ. Ví dụ: điều này phù hợp với PEP 484

from collections.abc import Sequence

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

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

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

PEP 544 cho phép giải quyết vấn đề này bằng cách cho phép người dùng viết đoạn mã trên mà không có các lớp cơ sở rõ ràng trong định nghĩa lớp, cho phép

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
61 được ngầm coi là một kiểu con của 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]]
62 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]]
63 bởi trình kiểm tra kiểu tĩnh. Điều này được gọi là phân nhóm cấu trúc [hoặc phân nhóm tĩnh]

from collections.abc import Sequence

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

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

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

Ngoài ra, bằng cách phân lớp một lớp đặc biệt, người dùng có thể xác định các giao thức tùy chỉnh mới để tận hưởng đầy đủ phân nhóm cấu trúc [xem ví dụ bên dưới]

nội dung mô-đun

Mô-đun định nghĩa các lớp, chức năng và trình trang trí sau

Ghi chú

Mô-đun này xác định một số loại là các lớp con của các lớp thư viện tiêu chuẩn đã tồn tại từ trước, cũng mở rộng để hỗ trợ các biến loại bên trong

Vector = list[float]

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

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

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

Các loại không dùng nữa sẽ bị xóa khỏi mô-đun trong phiên bản Python đầu tiên được phát hành 5 năm sau khi phát hành Python 3. 9. 0. Xem chi tiết trong PEP 585—Type Gợi ý Generics Trong Bộ sưu tập Tiêu chuẩn

Kiểu gõ đặc biệt

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

Chúng có thể được sử dụng làm loại trong 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]]
66

Vector = list[float]

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

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

Loại đặc biệt cho biết loại không bị ràng buộc

  • Mọi loại đều tương thích với
  • tương thích với mọi loại
Vector = list[float]

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

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

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

from collections.abc import Sequence

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

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

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

các hình thức đặc biệt

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

Vector = list[float]

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

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

Loại tuple; . Loại của bộ dữ liệu 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]]
77

Thí 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]]
78 là một bộ gồm hai phần tử tương ứng với các biến kiểu 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]]
79 là một bộ gồm một số nguyên, một số float và một chuỗi

Để chỉ định một bộ có độ dài thay đổi thuộc loại đồng nhất, hãy sử dụng dấu chấm lửng bằng chữ, e. g.

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
80. Một đồng bằng 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]]
82, và đến lượt 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]]
84

loại hình công đoàn;

Để xác định một công đoàn, sử dụng e. g.

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
86. Thông tin chi tiết

  • Các đối số phải là các loại và phải có ít nhất một
  • Liên minh công đoàn bị san phẳng, đ. g

    from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message[message: str, servers: Sequence[Server]] -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message[
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
        ...
    
    5
  • Liên minh của một đối số duy nhất biến mất, e. g

    from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message[message: str, servers: Sequence[Server]] -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message[
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
        ...
    
    6
  • Đối số dư thừa được bỏ qua, e. g

    from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message[message: str, servers: Sequence[Server]] -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message[
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
        ...
    
    7
  • Khi so sánh các công đoàn, thứ tự đối số bị bỏ qua, e. g

    from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message[message: str, servers: Sequence[Server]] -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message[
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
        ...
    
    8
  • Bạn không thể phân lớp hoặc khởi tạo một liên minh
  • 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]]
    
    87
  • Bạn có thể 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]]
    
    88 như một cách viết tắt 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]]
    
    89

Thay đổi trong phiên bản 3. 7. Không xóa các lớp con rõ ràng khỏi các liên kết trong thời gian chạy

Vector = list[float]

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

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

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]]
88 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]]
89

Lưu ý rằng đây không phải là khái niệm giống như đối số tùy chọn, là đối số có giá trị mặc định. Đối số tùy chọn với giá trị mặc định không yêu cầu từ 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]]
93 trên 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:
    ...
9

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

from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
1 được cho phép, thì 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]]
93 là phù hợp, cho dù đối số có phải là tùy chọn hay không. Ví dụ

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
0_______5_______96

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

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

Không có cú pháp để chỉ ra các đối số tùy chọn hoặc từ khóa; .

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
18 [dấu chấm lửng theo nghĩa đen] có thể được sử dụng để nhập gợi ý có thể gọi được, lấy bất kỳ số lượng đối số nào và trả về
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
99. Một đồng bằng 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:
    ...
01, và đến lượt 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:
    ...
03

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:
    ...
04 có thể chấp nhận giá trị kiể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:
    ...
04. Ngược lại, một biến được chú thích bằng
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
06 có thể chấp nhận các giá trị là chính các lớp – cụ thể, nó sẽ chấp nhận đối tượng lớp của
from collections.abc import Sequence

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

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

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
1

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:
    ...
06 là hiệp phương sai

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
2

Việ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:
    ...
06 là biến thể 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:
    ...
04 nên triển khai cùng một chữ ký hàm tạo và chữ ký phương thức lớp 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:
    ...
04. Trình kiểm tra loại sẽ gắn cờ vi phạm điều này, nhưng cũng nên cho phép các lệnh gọi hàm tạo trong các lớp con khớp với các lệnh gọi hàm tạo trong lớp cơ sở được chỉ định. Cách trình kiểm tra loại được yêu cầu để xử lý trường hợp cụ thể này có thể thay đổi trong các phiên bản PEP 484 trong tương lai

Các tham số pháp lý duy nhất cho là các lớp, , và liên kết của bất kỳ loại nào trong số này. Ví dụ

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
3

from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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 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:
    ...
12, đến lượt nó 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:
    ...
16, là gốc của hệ thống phân cấp siêu dữ liệu của Python

from collections.abc import Sequence

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

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

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

Một loại có thể được sử dụng để chỉ ra cho người kiểm tra loại rằng tham số hàm hoặc biến tương ứng có giá trị tương đương với chữ được cung cấp [hoặc một trong số nhiều chữ]. Ví dụ

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
4

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
18 không thể được phân lớp. Trong thời gian chạy, một giá trị tùy ý được phép làm đối số kiểu cho
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
18, nhưng trình kiểm tra kiểu có thể áp đặt các hạn chế. Xem PEP 586 để biết thêm chi tiết về các loại chữ

from collections.abc import Sequence

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

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

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

Cấu trúc kiểu đặc biệt để đánh dấu các biến lớp

Như đã giới thiệu trong PEP 526, một chú thích biến được bao bọc trong ClassVar cho biết rằng một thuộc tính nhất định được dự định sử dụng làm biến lớp và không được đặt trên các phiên bản của lớp đó. Cách sử dụng

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
5

chỉ chấp nhận các loại và không thể đăng ký thêm

bản thân nó không phải là một lớp và không nên được sử dụng với hoặc. không thay đổi hành vi thời gian chạy Python, nhưng nó có thể được sử dụng bởi trình kiểm tra loại của bên thứ ba. Ví dụ: trình kiểm tra loại có thể gắn cờ mã sau đây là lỗi

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
6
from collections.abc import Sequence

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

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

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

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
7

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

from collections.abc import Sequence

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

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

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

Một loại, được giới thiệu trong PEP 593 [_______6_______28], để trang trí các loại hiện có với siêu dữ liệu theo ngữ cảnh cụ thể [có thể là nhiều phần của nó, vì

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
29 là biến thể]. Cụ thể, loại
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
22 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:
    ...
31 thông qua gợi ý đánh má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:
    ...
32. Siêu dữ liệu này có thể được sử dụng cho phân tích tĩnh hoặc trong thời gian chạy. Nếu một thư viện [hoặc công cụ] gặp một gợi ý đánh máy
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
32 và không có logic đặc biệt nào 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:
    ...
31, thì thư viện đó nên bỏ qua nó và chỉ coi loại đó là
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
22. 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:
    ...
36 hiện có trong mô-đun
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
68 vô hiệu hóa hoàn toàn các chú thích kiểm tra đánh máy trên một hàm hoặc một lớp, loại
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
29 cho phép cả kiểm tra đánh máy tĩnh 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]]
22 [e. g. , thông qua mypy hoặc Pyre, 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:
    ...
31] cùng với quyền truy cập thời gian chạy 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:
    ...
31 trong một ứng dụng cụ thể

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
29. Một công cụ hoặc thư viện gặp 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:
    ...
29 có thể quét qua các chú thích để xác định xem chúng có đáng quan tâm hay không [e. g. , sử dụng
from collections.abc import Sequence

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

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

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

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

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

Vì 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:
    ...
29 cho phép bạn đặt một số chú thích cùng [hoặc khác] loại trên bất kỳ nút nào, các công cụ hoặc thư viện sử dụng các chú thích đó chịu trách nhiệm xử lý các bản sao tiềm nă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]
8

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:
    ...
46 để cho phép một người truy cập các chú thích bổ sung khi chạy

Chi tiết cú pháp

  • Đối số đầu tiê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:
        ...
    
    29 phải là loại hợp lệ
  • Nhiều loại chú thích được hỗ trợ [_______6_______29 hỗ trợ các đối số biến đổi]

    from typing import NewType
    
    UserId = NewType['UserId', int]
    some_id = UserId[524313]
    
    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:
        ...
    
    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:
        ...
    
    51 không hợp lệ]
  • Thứ tự của các chú thích được giữ nguyên và các vấn đề cần kiểm tra bằ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]
    
    0
  • Các 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:
        ...
    
    29 lồng nhau được làm phẳng, với siêu dữ liệu được sắp xếp bắt đầu bằng chú thích trong cùng

    def get_user_name[user_id: UserId] -> str:
        ...
    
    # typechecks
    user_a = get_user_name[UserId[42351]]
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name[-1]
    
    1
  • Các chú thích trùng lặp không bị xóa

    def get_user_name[user_id: UserId] -> str:
        ...
    
    # typechecks
    user_a = get_user_name[UserId[42351]]
    
    # does not typecheck; an int is not a UserId
    user_b = get_user_name[-1]
    
    2
  • from collections.abc import Sequence
    
    ConnectionOptions = dict[str, str]
    Address = tuple[str, int]
    Server = tuple[Address, ConnectionOptions]
    
    def broadcast_message[message: str, servers: Sequence[Server]] -> None:
        ...
    
    # The static type checker will treat the previous type signature as
    # being exactly equivalent to this one.
    def broadcast_message[
            message: str,
            servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
        ...
    
    29 có thể được sử dụng với bí danh lồng nhau và bí danh 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]
    
    3

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

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

from collections.abc import Sequence

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

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

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

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

Một kiểu chung thường được khai báo bằng cách kế thừa từ một phần khởi tạo của lớp này với một hoặc nhiều biến kiểu. 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]
4

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]
5
from collections.abc import Sequence

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

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

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

Loại biến

Cách 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]
6

Biến loại tồn tại chủ yếu vì lợi ích của trình kiểm tra loại tĩnh. Chúng đóng vai trò là tham số cho các kiểu chung cũng như cho các định nghĩa hàm chung. Xem để biết thêm thông tin về các loại chung. Các 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]
7

Chữ ký của ví dụ sau về cơ bản là sự quá tải 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:
    ...
57 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:
    ...
58. Cũng lưu ý rằng nếu các đối số là thể hiện của một số lớp con của , thì kiểu trả về vẫn đơn giản

Khi 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:
    ...
61 sẽ tăng. Nói chung, và không nên được sử dụng với các loại

Biến loại có thể được đánh dấu hiệp biến hoặc chống biến bằng cách 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:
    ...
65 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. 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. Ngoài ra, một biến loại có thể chỉ định giới hạn trên bằng cách sử dụng
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
67. Điều này có nghĩa là một loại thực tế được thay thế [rõ ràng hoặc ngầm định] cho biến loại phải là một lớp con của loại ranh giới, xem PEP 484

from collections.abc import Sequence

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

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

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
69 là một biến kiểu được định nghĩa 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:
    ...
70

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 lẫn. 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]
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:
    ...
71

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

def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

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

Các lớp như vậy chủ yếu được sử dụng với các trình kiểm tra kiểu tĩnh nhận biết kiểu con cấu trúc [gõ vịt tĩnh], chẳng hạn

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
0

Xem PEP 544 để biết chi tiết. Các lớp giao thức được trang trí [được mô tả sau] hoạt động như các giao thức thời gian chạy đơn giản chỉ kiểm tra sự hiện diện của các thuộc tính nhất định, bỏ qua các chữ ký loại của chúng

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

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
1

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

Một giao thức như vậy có thể được sử dụng với và. Điều này tăng lên khi áp dụng cho một lớp phi giao thức. Điều này cho phép kiểm tra cấu trúc đơn giản, rất giống với “one trick pony” chẳng hạn như. Ví dụ

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
2

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

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

from collections.abc import Sequence

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

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

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

Phiên bản đánh máy của

Cách sử dụng

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
3

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

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
4

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

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
5

Các trường có giá trị mặc định phải xuất hiện sau bất kỳ trường nào không có giá trị mặc định

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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 đưa ra một lệnh ánh xạ tên trường với các loại trường. [Các tên trường nằm trong thuộc tính
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
81 và các giá trị mặc định nằm trong thuộc tính
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
82, cả hai đều là một phần của API nametuple. ]

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
83 lớp con cũng có thể có chuỗi tài liệu và phương thức

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
6

Sử dụng tương thích ngược

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
7

Thay đổi trong phiên bản 3. 6. Đã thêm hỗ trợ cho cú pháp chú thích biến PEP 526

Thay đổi trong phiên bản 3. 6. 1. Đã thêm hỗ trợ cho các giá trị, phương thức và chuỗi tài liệu mặc định

Thay đổi trong phiên bản 3. 8. Các thuộc tính

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
84 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:
    ...
80 hiện là từ điển thông thường thay vì phiên bả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:
    ...
86

Thay đổi trong phiên bản 3. 9. Đã xóa thuộc tính

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
84 để thay bằng thuộc tính
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
80 tiêu chuẩn hơn có cùng thông tin

from collections.abc import Sequence

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

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

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

Hàm trợ giúp để chỉ ra một loại khác biệt cho trình kiểm tra đánh máy, xem. Khi chạy, nó trả về một hàm trả về đối số của nó. Cách sử dụng

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
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:
    ...
90

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

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
92 khai báo một loại từ điển yêu cầu tất cả các phiên bản của nó có một bộ khóa nhất định, trong đó mỗi khóa được liên kết với một giá trị của một loại nhất quán. Kỳ vọng này không được kiểm tra trong thời gian chạy mà chỉ được thực thi bởi trình kiểm tra loại. Cách sử dụng

# 'output' is of type 'int', not 'UserId'
output = UserId[23413] + UserId[54341]
9

Có thể truy cập thông tin loại để xem xét nội tâm qua

from collections.abc import Sequence

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

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

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

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

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

# The static type checker will treat the previous 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. Để cho phép sử dụng tính năng này với các phiên bản Python cũ hơn không hỗ trợ PEP 526,
from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
92 hỗ trợ thêm hai dạng cú pháp tương đương

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
0

Theo mặc định, tất cả các khóa phải có trong TypedDict. Có thể ghi đè điều này bằng cách chỉ định tổng số. Cách sử dụng

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
1

Điều này có nghĩa là một point2D TypedDict có thể bỏ qua bất kỳ phím nào. Trình kiểm tra loại chỉ được mong đợi hỗ trợ một chữ Sai hoặc Đúng làm giá trị của đối số tổng. True là mặc định và bắt buộc phải có tất cả các mục được xác định trong nội dung lớp

Xem PEP 589 để biết thêm ví dụ và quy tắc chi tiết về việc sử dụng

from collections.abc import Sequence

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

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

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

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

Tương ứng với các loại tích 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:
    ...
97

Một phiên bản chung của. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nên sử dụng loại bộ sưu tập trừu tượng, chẳng hạn như

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

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
2______9_______00

Phiên bản chung của. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nên sử dụng một loại tập hợp trừu tượng như hoặc

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

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
3____9_______04

Một phiên bản chung của. Hữu ích cho việc chú thích các loại trả lại. Để chú thích các đối số, nên sử dụng loại bộ sưu tập trừu tượng, chẳng hạn như

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
07

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

Ghi chú

là một hình thức đặc biệt

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
11

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
13

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
15

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
17

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
19

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

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
21
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
22
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
23

Loại chung

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
24 và các lớp con của nó
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
25 và
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
26 đại diện cho các loại luồng I/O chẳng hạn như được trả về bởi. Các loại này cũng nằm trong không gian tên
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
28

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
29
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
30

Các bí danh loại này tương ứng với các loại trả về từ và. Các loại này [và các chức năng tương ứng] là chung chung trong

from collections.abc import Sequence

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

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

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message[
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]] -> None:
    ...
69 và có thể được cụ thể hóa bằng cách viết
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
34,
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
35,
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
36 hoặc
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
37. Các loại này cũng nằm trong không gian tên
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
38

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
39

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
40 là bí danh của
from collections.abc import Callable

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

def async_query[on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]] -> None:
    # Body
7. Nó được cung cấp để cung cấp đường dẫn tương thích chuyển tiếp cho mã Python 2. trong Python 2,
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
40 là bí danh của
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
43

Sử dụng

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
40 để chỉ ra rằng một giá trị phải chứa chuỗi unicode theo cách tương thích với cả Python 2 và Python 3

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
4

Các lớp cơ sở trừu tượng

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
46

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
48

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

Loại này đại diện cho các loại , và của các chuỗi byte

Là cách viết tắt của loại này, có thể được sử dụng để chú thích đối số của bất kỳ loại nào được đề cập ở trên

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
54

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
56

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
58

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
60

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
62

Một phiên bản chung của. Loại này có thể được sử dụng như sau

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
5
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
64

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
66

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
68

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
70

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
72

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
74

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

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
77

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
79

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
81

Trình tạo có thể được chú thích theo loại chung

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
82. Ví dụ

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
6

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
83 của hoạt động trái ngược, không đồng biến hoặc bất biến

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
83 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]]
99 thành
from collections.abc import Mapping, Sequence

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

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
7

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
88 hoặc
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
89

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
8
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
90

Một bí danh cho

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
92

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
94

Một bí danh cho

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
96

Một phiên bản chung của. Phương sai và thứ tự của các biến loại tương ứng với biến của , ví dụ

from typing import NewType

UserId = NewType['UserId', int]

# Fails at runtime and does not typecheck
class AdminUserId[UserId]: pass
9_______9_______99

Trình tạo không đồng bộ có thể được chú thích theo 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]
00. Ví dụ

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
0

Không giống như các trình tạo thông thường, trình tạo không đồng bộ không thể trả về giá trị, vì vậy không có tham số loại

Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
99. Như với ,
from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
83 hoạt động trái ngược

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

from typing import NewType

UserId = NewType['UserId', int]
some_id = UserId[524313]
83 thành
from collections.abc import Mapping, Sequence

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

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
1

Ngoài ra, hãy chú thích trình tạo của bạn có kiểu trả về 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]
06 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]
07

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
2
def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

# does not typecheck; an int is not a UserId
user_b = get_user_name[-1]
08

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

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

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

Các loại trình quản lý bối cả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]
14

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

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

giao thức

Các giao thức này được trang trí với

def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

# does not typecheck; an int is not a UserId
user_b = get_user_name[-1]
19

Một ABC với một phương thức trừu tượ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]
20 đồng biến trong kiểu trả về 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]
21

Một ABC với một phương pháp trừu tượ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]
22

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

Một ABC với một phương pháp trừu tượ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]
24

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

Một ABC với một phương pháp trừu tượ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]
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]
27

Một ABC với một phương pháp trừu tượ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]
28

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

Một ABC với một phương pháp trừu tượ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]
30

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

Một ABC với một phương thức trừu tượ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]
32 đồng biến trong kiểu trả về của nó

Chức năng và trang trí

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

Truyền một giá trị cho một loại

Điều này trả về giá trị không thay đổi. Đối với trình kiểm tra loại, điều này báo hiệu rằng giá trị trả về có loại được chỉ định, nhưng trong thời gian chạy, chúng tôi cố tình không kiểm tra bất kỳ thứ gì [chúng tôi muốn điều này càng nhanh càng tốt]

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

Trình trang trí

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 cho phép mô tả các hàm và phương thức hỗ trợ nhiều kiểu kết hợp đối số khác nhau. Một loạt các định nghĩa được trang trí ____10_______35 phải được theo sau bởi chính xác một định nghĩa không được trang trí ____10_______35 [cho cùng một chức năng/phương pháp]. Các định nghĩa được trang trí
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 chỉ dành cho lợi ích của trình kiểm tra loại, vì chúng sẽ bị ghi đè bởi định nghĩa không được trang trí ____10_______35, trong khi định nghĩa sau được sử dụng trong thời gian chạy nhưng trình kiểm tra loại sẽ bỏ qua. Trong thời gian chạy, việc gọi trực tiếp một hàm được trang trí
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 sẽ tăng. Một ví dụ về quá tải cung cấp một loại chính xác hơn có thể được biểu thị bằng cách sử dụng liên kết hoặc biến loại

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
3

Xem PEP 484 để biết chi tiết và so sánh với các ngữ nghĩa đánh máy khác

def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

# does not typecheck; an int is not a UserId
user_b = get_user_name[-1]
42

Một trình trang trí để chỉ ra cho người kiểm tra loại rằng phương thức được trang trí không thể bị ghi đè và lớp được trang trí không thể được phân lớp. Ví dụ

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
4

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

def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

# does not typecheck; an int is not a UserId
user_b = get_user_name[-1]
43

Trình trang trí để chỉ ra rằng các chú thích không phải là gợi ý loại

Điều này hoạt động như lớp hoặc chức năng. Với một lớp, nó áp dụng đệ quy cho tất cả các phương thức được định nghĩa trong lớp đó [nhưng không áp dụng cho các phương thức được định nghĩa trong lớp cha hoặc lớp con của nó]

Điều này làm thay đổi [các] chức năng tại chỗ

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

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

Điều này bao bọc trình trang trí bằng thứ gì đó bao bọc chức năng được trang trí trong

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

Trình trang trí để đánh dấu một lớp hoặc chức năng không khả dụng khi chạy

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

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
5

Lưu ý rằng không nên trả lại các phiên bản của các lớp riêng tư. Tốt nhất là công khai các lớp như vậy

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

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

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

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

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. Ngoài ra, các tham chiếu chuyển tiếp được mã hóa dưới dạng chuỗi ký tự được xử lý bằng cách đánh giá chúng trong các không gian tên
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]
50 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]
51. Nếu cầ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]
52 được thêm vào cho chú thích hàm và phương thức nếu giá trị mặc định bằng
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
1 đượ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:
    ...
04, 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ả cá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:
    ...
80 cùng 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]
56 theo thứ tự ngược lại

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

def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

# does not typecheck; an int is not a UserId
user_b = get_user_name[-1]
57 bằng
Vector = list[float]

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

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale[2.0, [1.0, -4.2, 5.4]]
22, trừ khi
def get_user_name[user_id: UserId] -> str:
    ...

# typechecks
user_a = get_user_name[UserId[42351]]

# does not typecheck; an int is not a UserId
user_b = get_user_name[-1]
59 được đặt thà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]
60 [xem để biết thêm thông tin]. Ví dụ

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
6

Thay đổi trong phiên bản 3. 9. Đã thêm 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]
59 như một phần của PEP 593

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

Cung cấp nội quan cơ bản cho các loại chung và các hình thức gõ đặc biệt

Đối với một đối tượng gõ có dạng

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]
65, các hàm này 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]
66 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]
67. Nếu
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]
66 là bí danh chung cho nội trang hoặc lớp, nó sẽ được chuẩn hóa thành lớp ban đầu. Đối với các đối tượng không được hỗ trợ, hãy trả lại
from collections.abc import Mapping, Sequence

def notify_by_email[employees: Sequence[Employee],
                    overrides: Mapping[str, str]] -> None: ...
1 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]
71 tương ứng. ví dụ

from typing import NewType

UserId = NewType['UserId', int]

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

Một lớp được sử dụng để biểu diễn kiểu gõ bên trong của các tham chiếu chuyển tiếp chuỗi. 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]
73 được chuyển đổi ngầm thà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]
74. Lớp này không nên được khởi tạo bởi người dùng, nhưng có thể được sử dụng bởi các công cụ hướng nội

Hằng 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]
75

Một hằng số đặc biệt được giả định 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]
60 bởi 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]
77 trong thời gian chạy. Cách sử dụng

from typing import NewType

UserId = NewType['UserId', int]

ProUserId = NewType['ProUserId', UserId]
8

Chú thích loại đầu tiên phải được đặt trong dấu ngoặc kép, làm cho nó trở thành "tham chiếu chuyển tiếp", để ẩn tham chiếu

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]
78 khỏi thời gian chạy trình thông dịch. Loại chú thích cho các biến cục bộ không được đánh giá, vì vậy chú thích thứ hai không cần phải được đặt trong dấu ngoặc kép

Ghi chú

Nếu

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]
79 được sử dụng trong Python 3. 7 trở lên, các chú thích không được đánh giá tại thời điểm định nghĩa hàm. Thay vào đó, chúng được lưu trữ dưới dạng chuỗi trong
from collections.abc import Sequence

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

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

# The static type checker will treat the previous 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, Điều này khiến cho việc sử dụng dấu ngoặc kép xung quanh chú thích là không cần thiết. [xem PEP 563]

Chủ Đề