# `typing` --- 支援型別提示

在 3.5 版被加入.

原始碼：Lib/typing.py

備註

Python runtime 不強制要求函式與變數的型別註釋。他們可以被第三方工具使用，如：型別檢查器、IDE、linter 等。

此模組提供 runtime 型別提示支援。

動腦筋思考下面的函式：

    def surface_area_of_cube(edge_length: float) -> str:
        return f"The surface area of the cube is {6 * edge_length ** 2}."

函式 `surface_area_of_cube` 需要一個引數且預期是一個 `float` 的實例，如 `edge_length: float` 所指出的型別提示。這個函式預期會回傳一個 `str` 的實例，如 `-> str` 所指出的提示。

儘管型別提示可以是簡單類別，像是 `float` 或 `str`，他們也可以變得更為複雜。模組 `typing` 提供一組更高階的型別提示詞彙。

新功能會頻繁的新增至 `typing` 模組中。typing_extensions 套件為這些新功能提供了 backport（向後移植的）版本，提供給舊版本的 Python 使用。

也參考

型別小抄 (Typing cheat sheet)

  型別提示的快速預覽（發布於 mypy 的文件中）

mypy 文件的 型別系統參考資料 (Type System Reference) 章節

  Python 的加註型別系統是基於 PEPs 進行標準化，所以這個參照 (reference) 應該在多數 Python 型別檢查器中廣為使用。（某些部分依然是特定給 mypy 使用。）

Python 的靜態型別 (Static Typing)

  由社群編寫的跨平台型別檢查器文件 (type-checker-agnostic) 詳細描述加註型別系統的功能、實用的加註型別衍伸工具、以及加註型別的最佳實踐 (best practice)。

## Python 型別系統的技術規範

關於 Python 型別系統標準的 (canonical)、最新的技術規範可以在Python 型別系統的技術規範找到。

## 型別別名

一個型別別名被定義來使用 `type` 陳述式，其建立了 `TypeAliasType` 的實例。在這個範例中，`Vector` 及 `list[float]` 會被當作和靜態型別檢查器一樣同等對待：

    type Vector = list[float]

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

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

型別別名對於簡化複雜的型別簽名 (complex type signature) 非常好用。舉例來說：

    from collections.abc import Sequence

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

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

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

`type` 陳述式是 Python 3.12 的新功能。為了向後相容性，型別別名可以透過簡單的賦值來建立：

    Vector = list[float]

或是用 `TypeAlias` 標記，讓它明確的表示這是一個型別別名，而非一般的變數賦值：

    from typing import TypeAlias

    Vector: TypeAlias = list[float]

## NewType

使用 `NewType` 輔助工具 (helper) 建立獨特型別：

    from typing import NewType

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

若它是原本型別的子類別，靜態型別檢查器會將其視為一個新的型別。這對於幫助擷取邏輯性錯誤非常有用：

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

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

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

你依然可以在對於型別 `UserId` 的變數中執行所有 `int` 的操作。這讓你可以在預期接受 `int` 的地方傳遞一個 `UserId`，還能預防你意外使用無效的方法建立一個 `UserId`：

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

注意這只會透過靜態型別檢查器強制檢查。在 runtime 中，陳述式 (statement) `Derived = NewType('Derived', Base)` 會使 `Derived` 成為一個 callable（可呼叫物件），會立即回傳任何你傳遞的引數。這意味著 expression （運算式）`Derived(some_value)` 不會建立一個新的類別或過度引入原有的函式呼叫。

更精確地說，expression `some_value is Derived(some_value)` 在 runtime 永遠為 true。

這會無法建立一個 `Derived` 的子型別：

    from typing import NewType

    UserId = NewType('UserId', int)

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

無論如何，這有辦法基於 '衍生的' `NewType` 建立一個 `NewType`：

    from typing import NewType

    UserId = NewType('UserId', int)

    ProUserId = NewType('ProUserId', UserId)

以及針對 `ProUserId` 的型別檢查會如期運作。

更多細節請見 PEP 484。

備註

請記得使用型別別名是宣告兩種型別是互相相等的。使用 `type Alias = Original` 則會讓靜態型別檢查器在任何情況之下將 `Alias` 視為與 `Original` 完全相等。這當你想把複雜的型別簽名進行簡化時，非常好用。

相反的，`NewType` 宣告一個型別會是另外一種型別的子類別。使用 `Derived = NewType('Derived', Original)` 會使靜態型別檢查器將 `Derived` 視為 `Original` 的子類別，也意味著一個型別為 `Original` 的值，不能被使用在任何預期接收到型別 `Derived` 的值的區域。這當你想用最小的 runtime 成本預防邏輯性錯誤而言，非常有用。

在 3.5.2 版被加入.

在 3.10 版的變更: 現在的 `NewType` 比起一個函式更像一個類別。因此，比起一般的函式，呼叫 `NewType` 需要額外的 runtime 成本。

在 3.11 版的變更: 呼叫 `NewType` 的效能已經恢復與 Python 3.9 相同的水準。

## 註釋 callable 物件

函式，或者是其他 callable 物件，可以使用 `collections.abc.Callable` 或以棄用的 `typing.Callable` 進行註釋。 `Callable[[int], str]` 象徵為一個函式，可以接受一個型別為 `int` 的引數，並回傳一個 `str`。

舉例來說：

    from collections.abc import Callable, Awaitable

    def feeder(get_next_item: Callable[[], str]) -> None:
        ...  # 主體

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

    async def on_update(value: str) -> None:
        ...  # 主體

    callback: Callable[[str], Awaitable[None]] = on_update

使用下標語法 (subscription syntax) 時，必須使用到兩個值，分別為引述串列以及回傳類別。引數串列必須為一個型別串列：`ParamSpec`、`Concatenate` 或是一個刪節號 (ellipsis, `...`)。回傳類別必為一個單一類別。

若刪節號字面值 `...` 被當作引數串列給定，其指出一個具任何、任意參數列表的 callable 會被接受：

    def concat(x: str, y: str) -> str:
        return x + y

    x: Callable[..., str]
    x = str     # OK
    x = concat  # 也 OK

`Callable` 不如有可變數量引數的函式、`overloaded functions`、或是僅限關鍵字參數的函式，可以表示複雜簽名。然而，這些簽名可以透過定義一個具有 `__call__()` 方法的 `Protocol` 類別進行表示：

    from collections.abc import Iterable
    from typing import Protocol

    class Combiner(Protocol):
        def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...

    def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
        for item in data:
            ...

    def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
        ...
    def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
        ...

    batch_proc([], good_cb)  # OK
    batch_proc([], bad_cb)   # Error! Argument 2 has incompatible type because of
                             # different name and kind in the callback

Callable 物件可以取用其他 callable 當作引數使用，可以透過 `ParamSpec` 指出他們的參數型別是個別獨立的。另外，如果這個 callable 從其他 callable 新增或刪除引數時，將會使用到 `Concatenate` 運算子。他們可以分別採用 `Callable[ParamSpecVariable, ReturnType]` 以及 `Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]` 的形式。

在 3.10 版的變更: `Callable` 現已支援 `ParamSpec` 以及 `Concatenate`。請參閱 PEP 612 閱讀詳細內容。

也參考

`ParamSpec` 以及 `Concatenate` 的文件中，提供範例如何在 `Callable` 中使用。

## 泛型

因為關於物件的型別資訊留存在容器之內，且無法使用通用的方式進行靜態推論 (statically inferred)，許多標準函式庫的容器類別支援以下標來表示容器內預期的元素。

    from collections.abc import Mapping, Sequence

    class Employee: ...

    # Sequence[Employee] indicates that all elements in the sequence
    # must be instances of "Employee".
    # Mapping[str, str] indicates that all keys and all values in the mapping
    # must be strings.
    def notify_by_email(employees: Sequence[Employee],
                        overrides: Mapping[str, str]) -> None: ...

泛型函式及類別可以使用型別參數語法 (type parameter syntax) 進行參數化 (parameterize) ：

    from collections.abc import Sequence

    def first[T](l: Sequence[T]) -> T:  # Function is generic over the TypeVar "T"
        return l[0]

或是直接使用 `TypeVar` 工廠 (factory)：

    from collections.abc import Sequence
    from typing import TypeVar

    U = TypeVar('U')                  # Declare type variable "U"

    def second(l: Sequence[U]) -> U:  # Function is generic over the TypeVar "U"
        return l[1]

在 3.12 版的變更: 在 Python 3.12 中，泛型的語法支援是全新功能。

## 註釋元組 (tuple)

在 Python 大多數的容器當中，加註型別系統認為容器內的所有元素會是相同型別。舉例來說：

    from collections.abc import Mapping

    # Type checker will infer that all elements in ``x`` are meant to be ints
    x: list[int] = []

    # Type checker error: ``list`` only accepts a single type argument:
    y: list[int, str] = [1, 'foo']

    # Type checker will infer that all keys in ``z`` are meant to be strings,
    # and that all values in ``z`` are meant to be either strings or ints
    z: Mapping[str, str | int] = {}

`list` 只接受一個型別引數，所以型別檢查器可能在上述 `y` 賦值 (assignment) 觸發錯誤。類似的範例，`Mapping` 只接受兩個型別引數：第一個引數指出 keys（鍵）的型別；第二個引數指出 values（值）的型別。

然而，與其他多數的 Python 容器不同，在慣用的 (idiomatic) Python 程式碼中，元組可以擁有不完全相同型別的元素是相當常見的。為此，元組在 Python 的加註型別系統中是個特例 (special-cased)。`tuple` 接受任何數量的型別引數：

    # OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int
    x: tuple[int] = (5,)

    # OK: ``y`` is assigned to a tuple of length 2;
    # element 1 is an int, element 2 is a str
    y: tuple[int, str] = (5, "foo")

    # Error: the type annotation indicates a tuple of length 1,
    # but ``z`` has been assigned to a tuple of length 3
    z: tuple[int] = (1, 2, 3)

為了標示一個元組可以為任意長度，且所有元素皆是相同型別 `T`，請使用 刪節號字面值 (literal ellipsis) `...`：`tuple[T, ...]`。為了標示一個空元組，請使用 `tuple[()]`。單純使用 `tuple` 作為註釋會與使用 `tuple[Any, ...]` 相等：

    x: tuple[int, ...] = (1, 2)
    # These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length
    x = (1, 2, 3)
    x = ()
    # This reassignment is an error: all elements in ``x`` must be ints
    x = ("foo", "bar")

    # ``y`` can only ever be assigned to an empty tuple
    y: tuple[()] = ()

    z: tuple = ("foo", "bar")
    # These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]``
    z = (1, 2, 3)
    z = ()

## 類別物件的型別

一個變數被註釋為 `C` 可以接受一個型別為 `C` 的值。相對的，一個變數備註解為 `type[C]` （或已棄用的 `typing.Type[C]`）可以接受本身為該類別的值 -- 具體來說，他可能會接受 `C` 的類別物件。舉例來說：

    a = 3         # Has type ``int``
    b = int       # Has type ``type[int]``
    c = type(a)   # Also has type ``type[int]``

請記得 `type[C]` 是共變 (covariant) 的：

    class User: ...
    class ProUser(User): ...
    class TeamUser(User): ...

    def make_new_user(user_class: type[User]) -> User:
        # ...
        return user_class()

    make_new_user(User)      # OK
    make_new_user(ProUser)   # Also OK: ``type[ProUser]`` is a subtype of ``type[User]``
    make_new_user(TeamUser)  # Still fine
    make_new_user(User())    # Error: expected ``type[User]`` but got ``User``
    make_new_user(int)       # Error: ``type[int]`` is not a subtype of ``type[User]``

`type` 僅有的合法參數是類別、`Any`、型別變數以及這些型別任意組合成的聯集。舉例來說：

    def new_non_team_user(user_class: type[BasicUser | ProUser]): ...

    new_non_team_user(BasicUser)  # OK
    new_non_team_user(ProUser)    # OK
    new_non_team_user(TeamUser)   # Error: ``type[TeamUser]`` is not a subtype
                                  # of ``type[BasicUser | ProUser]``
    new_non_team_user(User)       # Also an error

`type[Any]` 等價於 `type` ，其為 Python metaclass 階層結構 (hierachy)。

## Annotating generators and coroutines

A generator can be annotated using the generic type `Generator[YieldType, SendType, ReturnType]`. For example:

    def echo_round() -> Generator[int, float, str]:
        sent = yield 0
        while sent >= 0:
            sent = yield round(sent)
        return 'Done'

Note that unlike many other generic classes in the standard library, the `SendType` of `Generator` behaves contravariantly, not covariantly or invariantly.

The `SendType` and `ReturnType` parameters default to `None`:

    def infinite_stream(start: int) -> Generator[int]:
        while True:
            yield start
            start += 1

It is also possible to set these types explicitly:

    def infinite_stream(start: int) -> Generator[int, None, None]:
        while True:
            yield start
            start += 1

Simple generators that only ever yield values can also be annotated as having a return type of either `Iterable[YieldType]` or `Iterator[YieldType]`:

    def infinite_stream(start: int) -> Iterator[int]:
        while True:
            yield start
            start += 1

Async generators are handled in a similar fashion, but don't expect a `ReturnType` type argument (`AsyncGenerator[YieldType, SendType]`). The `SendType` argument defaults to `None`, so the following definitions are equivalent:

    async def infinite_stream(start: int) -> AsyncGenerator[int]:
        while True:
            yield start
            start = await increment(start)

    async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
        while True:
            yield start
            start = await increment(start)

As in the synchronous case, `AsyncIterable[YieldType]` and `AsyncIterator[YieldType]` are available as well:

    async def infinite_stream(start: int) -> AsyncIterator[int]:
        while True:
            yield start
            start = await increment(start)

Coroutines can be annotated using `Coroutine[YieldType, SendType, ReturnType]`. Generic arguments correspond to those of `Generator`, for example:

    from collections.abc import Coroutine
    c: Coroutine[list[str], str, int]  # Some coroutine defined elsewhere
    x = c.send('hi')                   # Inferred type of 'x' is list[str]
    async def bar() -> None:
        y = await c                    # Inferred type of 'y' is int

## 使用者定義泛型型別

一個使用者定義的類別可以被定義成一個泛型類別。

    from logging import Logger

    class LoggedVar[T]:
        def __init__(self, value: T, name: str, logger: Logger) -> None:
            self.name = name
            self.logger = logger
            self.value = value

        def set(self, new: T) -> None:
            self.log('Set ' + repr(self.value))
            self.value = new

        def get(self) -> T:
            self.log('Get ' + repr(self.value))
            return self.value

        def log(self, message: str) -> None:
            self.logger.info('%s: %s', self.name, message)

這個語法指出類別 `LoggedVar` 透過一個單一的 型別變數 `T` 進行參數化 (parameterised)。這使得 `T` 在類別中有效的成為型別。

泛型類別隱性繼承了 `Generic`。為了相容 Python 3.11 及更早版本，也可以明確的繼承 `Generic` 並指出是一個泛型類別：

    from typing import TypeVar, Generic

    T = TypeVar('T')

    class LoggedVar(Generic[T]):
        ...

泛型類別有 `__class_getitem__()` 方法，其意味著可以在 runtime 進行參數化（如下述的 `LoggedVar[int]`）：

    from collections.abc import Iterable

    def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
        for var in vars:
            var.set(0)

一個泛型型別可以有任意數量的型別變數。所有種類的 `TypeVar` 都可以作為泛型型別的參數：

    from typing import TypeVar, Generic, Sequence

    class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:
        ...

    OldT = TypeVar('OldT', contravariant=True)
    OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)
    OldS = TypeVar('OldS', int, str)

    class OldWeirdTrio(Generic[OldT, OldB, OldS]):
        ...

`Generic` 的每個型別變數引數必不相同。因此以下是無效的：

    from typing import TypeVar, Generic
    ...

    class Pair[M, M]:  # SyntaxError
        ...

    T = TypeVar('T')

    class Pair(Generic[T, T]):   # INVALID
        ...

泛型類別亦可以繼承其他類別：

    from collections.abc import Sized

    class LinkedList[T](Sized):
        ...

當繼承泛型類別時，部份的型別參數可固定：

    from collections.abc import Mapping

    class MyDict[T](Mapping[str, T]):
        ...

在這種情況下 `MyDict` 有一個單一的參數 `T`。

若使用泛型類別卻沒有特指型別參數，則會將每個位置視為 `Any`。在下列的範例中 `MyIterable` 不是泛型，但隱性繼承了 `Iterable[Any]`：

    from collections.abc import Iterable

    class MyIterable(Iterable): # Same as Iterable[Any]
        ...

使用者定義的泛型型別別名也有支援。例如：

    from collections.abc import Iterable

    type Response[S] = Iterable[S] | int

    # Return type here is same as Iterable[str] | int
    def response(query: str) -> Response[str]:
        ...

    type Vec[T] = Iterable[tuple[T, T]]

    def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
        return sum(x*y for x, y in v)

為了向後相容性，泛型型別別名可以透過簡單的賦值來建立：

    from collections.abc import Iterable
    from typing import TypeVar

    S = TypeVar("S")
    Response = Iterable[S] | int

在 3.7 版的變更: `Generic` 不再是一個自訂的 metaclass。

在 3.12 版的變更: 在版本 3.12 新增了泛型及型別別名的語法支援。在之前的版本中，泛型類別必須顯性繼承 `Generic` 或是包含一個型別變數在基底類別 (base) 當中。

使用者定義的參數運算式 (parameter expression) 泛型一樣有支援，透過 `[**P]` 格式的參數規格變數來進行表示。對於上述作為參數規格變數的型別變數，將持續被 `typing` 模組視為一個特定的型別變數。對此，其中一個例外是一個型別列表可以替代 `ParamSpec`：

    >>> class Z[T, **P]: ...  # T 為 TypeVar；P 為 ParamSpec
    ...
    >>> Z[int, [dict, float]]
    __main__.Z[int, [dict, float]]

具有 `ParamSpec` 的泛型類別可以透過顯性繼承 `Generic` 進行建立。在這種情況下，不需要使用 `**`：

    from typing import ParamSpec, Generic

    P = ParamSpec('P')

    class Z(Generic[P]):
        ...

另外一個 `TypeVar` 以及 `ParamSpec` 之間的差異是，基於美觀因素，只有一個參數規格變數的泛型可以接受如 `X[[Type1, Type2, ...]]` 以及 `X[Type1, Type2, ...]` 的參數列表。在內部中，後者會被轉換為前者，所以在下方的範例中為相等的：

    >>> class X[**P]: ...
    ...
    >>> X[int, str]
    __main__.X[[int, str]]
    >>> X[[int, str]]
    __main__.X[[int, str]]

請記得，具有 `ParamSpec` 的泛型在某些情況下替換之後可能不會有正確的 `__parameters__`，因為參數規格主要還是用於靜態型別檢查。

在 3.10 版的變更: `Generic` 現在可以透過參數運算式來進行參數化。詳細內容請見 `ParamSpec` 以及 PEP 612。

一個使用者定義的泛型類別可以將 ABC 作為他們的基底類別，且不會有 metaclass 衝突。泛型的 metaclass 則不支援。參數化泛型的輸出將被存為快取，而在 `typing` 模組中多數的型別皆為 hashable 且可以比較相等性。

## `Any` 型別

`Any` 是一種特別的型別。一個靜態型別檢查器會將每個型別視為可相容於 `Any` 且 `Any` 也可以相容於每個型別。

這意味著如果在一個為 `Any` 的值上執行任何操作或呼叫方法是可行的，且可以賦值給任意變數：

    from typing import Any

    a: Any = None
    a = []          # OK
    a = 2           # OK

    s: str = ''
    s = a           # OK

    def foo(item: Any) -> int:
        # Passes type checking; 'item' could be any type,
        # and that type might have a 'bar' method
        item.bar()
        ...

請注意，當賦予型別為 `Any` 的值更精確的型別時，將不會執行任何型別檢查。舉例來說，靜態型別檢查器不會在 runtime 中，將 `a` 賦值給 `s` 的情況下回報錯誤，儘管 `s` 是被宣告為型別 `str` 卻接收到 `int` 的值！

另外，所有缺少回傳型別或參數型別的函式將會隱性預設為 `Any`：

    def legacy_parser(text):
        ...
        return data

    # A static type checker will treat the above
    # as having the same signature as:
    def legacy_parser(text: Any) -> Any:
        ...
        return data

當你需要混和動態及靜態的型別程式碼，這個行為允許 `Any` 被當作一個緊急出口 (escape hatch)使用。

`Any` 的行為對比 `object` 的行為。與 `Any` 相似，所有的型別會作為 `object` 的子型別。然而，不像 `Any`，反之不亦然：`object` 並不是一個其他型別的子型別。

這意味著當一個值的型別為 `object` 時，型別檢查器會拒絕幾乎所有的操作，並將賦予這個值到一個特定型別變數（或是當作回傳值使用）視為一個型別錯誤。舉例來說：

    def hash_a(item: object) -> int:
        # Fails type checking; an object does not have a 'magic' method.
        item.magic()
        ...

    def hash_b(item: Any) -> int:
        # Passes type checking
        item.magic()
        ...

    # Passes type checking, since ints and strs are subclasses of object
    hash_a(42)
    hash_a("foo")

    # Passes type checking, since Any is compatible with all types
    hash_b(42)
    hash_b("foo")

使用 `object` ，將指出在型別安全 (typesafe) 的習慣之下一個值可以為任意型別。使用 `Any`，將指出這個值是個動態型別。

## 標稱 (nominal) 子型別 vs 結構子型別

最初 PEP 484 定義 Python 靜態型別系統使用標稱子型別。這意味著只有 `A` 為 `B` 的子類別時，`A` 才被允許使用在預期是類別 `B` 出現的地方。

這個需求之前也被運用在抽象基底類別，例如 `Iterable`。這種方式的問題在於，一個類別需要顯式的標記來支援他們，這並不符合 Python 風格，也不像一個常見的慣用動態型別 Python 程式碼。舉例來說，下列程式碼符合 PEP 484：

    from collections.abc import Sized, Iterable, Iterator

    class Bucket(Sized, Iterable[int]):
        ...
        def __len__(self) -> int: ...
        def __iter__(self) -> Iterator[int]: ...

PEP 544 可以透過使用上方的程式碼，且在類別定義時不用顯式基底類別解決這個問題，讓 `Bucket` 被靜態型別檢查器隱性認為是 `Sized` 以及 `Iterable[int]` 兩者的子型別。這就是眾所周知的結構子型別（或是靜態鴨子型別）：

    from collections.abc import Iterator, Iterable

    class Bucket:  # 注意：沒有基底類別
        ...
        def __len__(self) -> int: ...
        def __iter__(self) -> Iterator[int]: ...

    def collect(items: Iterable[int]) -> int: ...
    result = collect(Bucket())  # Passes type check

而且，基於一個特別的型別 `Protocol` 建立子型別時，使用者可以定義新的協定並充份發揮結構子型別的優勢（請見下方範例）。

## 模組內容

模組 `typing` 定義了下列的類別、函式以及裝飾器。

### 特別型別原語 (primitive)

#### 特別型別

這些可以在註釋中做為型別。他們並不支援 `[]` 的下標使用。

typing.Any

  特別型別，指出一個不受約束 (unconstrained) 的型別。

  - 所有型別皆與 `Any` 相容。

  - `Any` 相容於所有型別。

  在 3.11 版的變更: `Any` 可以作為一個基礎類別。這對於在任何地方使用鴨子型別或是高度動態的型別，避免型別檢查器的錯誤是非常有用的。

typing.AnyStr

  一個不受約束的型別變數。

  定義：

      AnyStr = TypeVar('AnyStr', str, bytes)

  `AnyStr` 是對於函式有用的，他可以接受 `str` 或 `bytes` 引數但不可以將此兩種混合。

  舉例來說：

      def concat(a: AnyStr, b: AnyStr) -> AnyStr:
          return a + b

      concat("foo", "bar")    # OK, output has type 'str'
      concat(b"foo", b"bar")  # OK, output has type 'bytes'
      concat("foo", b"bar")   # Error, cannot mix str and bytes

  請注意，儘管他的名稱相近，`AnyStr` 與 `Any` 型別無關，更不代表是「任何字串」的意思。尤其，`AnyStr` 與 `str | bytes` 兩者不同且具有不同的使用情境：

      # Invalid use of AnyStr:
      # The type variable is used only once in the function signature,
      # so cannot be "solved" by the type checker
      def greet_bad(cond: bool) -> AnyStr:
          return "hi there!" if cond else b"greetings!"

      # The better way of annotating this function:
      def greet_proper(cond: bool) -> str | bytes:
          return "hi there!" if cond else b"greetings!"

  自從版本 3.13 後不推薦使用，將會自版本 3.18 中移除。: Deprecated in favor of the new type parameter syntax. Use `class A[T: (str, bytes)]: ...` instead of importing `AnyStr`. See PEP 695 for more details.

  In Python 3.16, `AnyStr` will be removed from `typing.__all__`, and deprecation warnings will be emitted at runtime when it is accessed or imported from `typing`. `AnyStr` will be removed from `typing` in Python 3.18.

typing.LiteralString

  特別型別，只包含文本字串。

  任何文本字串都相容於 `LiteralString`，對於另一個 `LiteralString` 亦是如此。然而，若是一個型別僅為 `str` 的物件則不相容。一個字串若是透過組合多個 `LiteralString` 型別的物件建立，則此字串也可以視為 `LiteralString`。

  舉例來說：

      def run_query(sql: LiteralString) -> None:
          ...

      def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
          run_query("SELECT * FROM students")  # OK
          run_query(literal_string)  # OK
          run_query("SELECT * FROM " + literal_string)  # OK
          run_query(arbitrary_string)  # 型別檢查錯誤
          run_query(  # 型別檢查錯誤
              f"SELECT * FROM students WHERE name = {arbitrary_string}"
          )

  `LiteralString` 對於敏感的 API 來說是有用的，其中任意的使用者產生的字串可能會產生問題。舉例來說，上面兩個案例中產生的型別檢查器錯誤是脆弱的且容易受到 SQL 注入攻擊。

  更多細節請見 PEP 675。

  在 3.11 版被加入.

typing.Never
typing.NoReturn

  `Never` 和 `NoReturn` 表示底部型別 (bottom type)，為一個沒有任何成員的型別。

  它們可以被用來代表一個不會回傳的函式，像是 `sys.exit()`：

      from typing import Never  # 或 NoReturn

      def stop() -> Never:
          raise RuntimeError('no way')

  或被用來定義一個不應被呼叫的函式，因為不會有有效的引數，、像是 `assert_never()`：

      from typing import Never  # or NoReturn

      def never_call_me(arg: Never) -> None:
          pass

      def int_or_str(arg: int | str) -> None:
          never_call_me(arg)  # type checker error
          match arg:
              case int():
                  print("It's an int")
              case str():
                  print("It's a str")
              case _:
                  never_call_me(arg)  # OK, arg is of type Never (or NoReturn)

  `Never` 以及 `NoReturn` 在型別系統中具有相同的意義且靜態型別檢查器會將兩者視為相等。

  在 3.6.2 版被加入: 新增 `NoReturn`。

  在 3.11 版被加入: 新增 `Never`。

typing.Self

  特別型別，用來表示目前類別之內 (enclosed class)。

  舉例來說：

      from typing import Self, reveal_type

      class Foo:
          def return_self(self) -> Self:
              ...
              return self

      class SubclassOfFoo(Foo): pass

      reveal_type(Foo().return_self())  # Revealed type is "Foo"
      reveal_type(SubclassOfFoo().return_self())  # Revealed type is "SubclassOfFoo"

  這個註釋在語意上相等於下列內容，且形式更為簡潔：

      from typing import TypeVar

      Self = TypeVar("Self", bound="Foo")

      class Foo:
          def return_self(self: Self) -> Self:
              ...
              return self

  一般來說，如果某個東西回傳 `self` 如上方的範例所示，你則應該使用 `Self` 做為回傳值的註釋。若 `Foo.return_self` 被註釋為回傳 `"Foo"`，則型別檢查器應該推論這個從 `SubclassOfFoo.return_self` 回傳的物件為 `Foo` 型別，而並非回傳 `SubclassOfFoo` 型別。

  其他常見的使用案例包含：

  - `classmethod` 被用來作為替代的建構函式 (constructor) 並回傳 `cls` 參數的實例。

  - 註釋一個回傳自己的 `__enter__()` 方法。

  當類別被子類別化時，若方法不保證回傳一個子類別的實例，你不應該使用 `Self` 作為回傳註釋：

      class Eggs:
          # Self would be an incorrect return annotation here,
          # as the object returned is always an instance of Eggs,
          # even in subclasses
          def returns_eggs(self) -> "Eggs":
              return Eggs()

  更多細節請見 PEP 673。

  在 3.11 版被加入.

typing.TypeAlias

  做為明確宣告一個型別別名 的特別註釋。

  舉例來說：

      from typing import TypeAlias

      Factors: TypeAlias = list[int]

  `TypeAlias` 在舊的 Python 版本中特別有用，其註釋別名可以用來進行傳遞參照 (forward reference)，因為對於型別檢查器來說，分辨這些別名與一般的變數賦值相當困難：

      from typing import Generic, TypeAlias, TypeVar

      T = TypeVar("T")

      # "Box" does not exist yet,
      # so we have to use quotes for the forward reference on Python <3.12.
      # Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
      # not a variable assignment to a string.
      BoxOfStrings: TypeAlias = "Box[str]"

      class Box(Generic[T]):
          @classmethod
          def make_box_of_strings(cls) -> BoxOfStrings: ...

  更多細節請見 PEP 613。

  在 3.10 版被加入.

  在 3.12 版之後被棄用: `TypeAlias` 被棄用，請改用 `type` 陳述式來建立 `TypeAliasType` 的實例，其自然可以支援傳遞參照的使用。請注意，雖然 `TypeAlias` 以及 `TypeAliasType` 提供相似的用途且具有相似的名稱，他們是不同的，且後者不是前者的型別。現在還沒有移除 `TypeAlias` 的計畫，但鼓勵使用者們遷移 (migrate) 至 `type` 陳述式。

#### 特別型式

這些在註釋中可以當作型別使用。他們全都支援 `[]` 的下標使用，但每個都具有獨特的語法。

class typing.Union

  聯集型別；`Union[X, Y]` 與 `X | Y` 是相等的，且都意味著 X 或 Y 兩者其一。

  為了定義聯集，例如可以使用 `Union[int, str]` 或是使用簡寫 (shorthand) `int | str`。使用這種簡寫是非常推薦的。詳細請看：

  - 引數必須為型別且必須有至少一個。

  - 聯集中的聯集會是扁平化的 (flattened)，舉例來說：

        Union[Union[int, str], float] == Union[int, str, float]

    However, this does not apply to unions referenced through a type alias, to avoid forcing evaluation of the underlying `TypeAliasType`:

        type A = Union[int, str]
        Union[A, float] != Union[int, str, float]

  - 單一引數的聯集會消失不見，舉例來說：

        Union[int] == int  # 實際上建構函式會回傳 int

  - 多餘的引數會被略過，舉例來說：

        Union[int, str, int] == Union[int, str] == int | str

  - 當比較聯集時，引數的順序會被忽略，舉例來說：

        Union[int, str] == Union[str, int]

  - 你不能建立 `Union` 的子類別或是實例。

  - 你不能寫成 `Union[X][Y]`。

  在 3.7 版的變更: 請勿在 runtime 中將顯性子類別從聯集中移除。

  在 3.10 版的變更: 現在可以將聯集寫成 `X | Y`。請見聯集型別運算式。

  在 3.14 版的變更: `types.UnionType` is now an alias for `Union`, and both `Union[int, str]` and `int | str` create instances of the same class. To check whether an object is a `Union` at runtime, use `isinstance(obj, Union)`. For compatibility with earlier versions of Python, use `get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType`.

typing.Optional

  `Optional[X]` 與 `X | None` 是相等的（或是 `Union[X, None]`）。

  請注意，這與具有預設值的選擇性引數 (optional argument) 不是相同的概念。一個具有預設值的選擇性引數的型別註釋中不具有 `Optional` 限定符 (qualifier)，單純的因為它就是選擇性的。舉例來說：

      def foo(arg: int = 0) -> None:
          ...

  另一方面，如果一個顯性的值 `None` 是被允許的，不論引數是不是選擇性的，`Optional` 都適用。舉例來說：

      def foo(arg: Optional[int] = None) -> None:
          ...

  在 3.10 版的變更: 現在可以將 Optional 寫成 `X | None`。請見聯集型別運算式。

typing.Concatenate

  用於註釋高階函式的特別型式。

  `Concatenate` 可以被用在可呼叫物件與 `ParamSpec` 的接合 (conjunction) 並註釋一個高階的 Callable 物件可以新增、移除、轉換另一個 Callable 物件的參數。使用方法是依照這個格式 `Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]`。`Concatenate` 目前只在 Callable 物件中第一個引數使用時有效。`Concatenate` 的最後一個參數必須為一個 `ParamSpec` 或是刪節號 (`...`)。

  舉例來說，註釋一個為裝飾過後的函式提供 `threading.Lock` 的裝飾器 `with_lock`，`Concatenate` 可以用於指出 `with_lock` 預期一個 Callable 物件，該物件可以接受 `Lock` 作為第一引數，並回傳一個具有不同型別簽名 Callable 物件。在這種情況下，`ParamSpec` 指出回傳的 Callable 物件的參數型別會依賴傳遞的 Callable 物件的參數型別：

      from collections.abc import Callable
      from threading import Lock
      from typing import Concatenate

      # Use this lock to ensure that only one thread is executing a function
      # at any time.
      my_lock = Lock()

      def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
          '''A type-safe decorator which provides a lock.'''
          def inner(*args: P.args, **kwargs: P.kwargs) -> R:
              # Provide the lock as the first argument.
              return f(my_lock, *args, **kwargs)
          return inner

      @with_lock
      def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
          '''Add a list of numbers together in a thread-safe manner.'''
          with lock:
              return sum(numbers)

      # We don't need to pass in the lock ourselves thanks to the decorator.
      sum_threadsafe([1.1, 2.2, 3.3])

  在 3.10 版被加入.

  也參考

  - PEP 612 -- 參數技術規範變數

  - `ParamSpec`

  - 註釋 callable 物件

typing.Literal

  特殊型別格式，用於定義「文本型別 (literal type)」。

  `Literal` 可以用於型別檢查器並指出註釋物件具有一個與提供的文本相同的值。

  舉例來說：

      def validate_simple(data: Any) -> Literal[True]:  # 永遠回傳 True
          ...

      type Mode = Literal['r', 'rb', 'w', 'wb']
      def open_helper(file: str, mode: Mode) -> str:
          ...

      open_helper('/some/path', 'r')      # 通過型別檢查
      open_helper('/other/path', 'typo')  # 型別檢查器中的錯誤

  `Literal[...]` 不可以進行子類別化。在 runtime 之中，任意的值是允許作為 `Literal[...]` 的型別引數，但型別檢查器可能會加強限制。更多有關文本型別的詳細資訊請看 PEP 586。

  其他細節：

  - 引數必須為文本值且必須有至少一個。

  - 巢狀的 `Literal` 會是扁平化的 (flattened)，舉例來說：

        assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3]

    However, this does not apply to `Literal` types referenced through a type alias, to avoid forcing evaluation of the underlying `TypeAliasType`:

        type A = Literal[1, 2]
        assert Literal[A, 3] != Literal[1, 2, 3]

  - 多餘的引數會被略過，舉例來說：

        assert Literal[1, 2, 1] == Literal[1, 2]

  - 當比較文本時，引數的順序會被忽略，舉例來說：

        assert Literal[1, 2] == Literal[2, 1]

  - 你不能建立 `Literal` 的子類別或是實例。

  - 你不能寫成 `Literal[X][Y]`。

  在 3.8 版被加入.

  在 3.9.1 版的變更: `Literal` 現在可以刪除重複 (de-deplicate) 的參數。`Literal` 物件的相等性比較不再依照相依性排序。`Literal` 物件現在會在相等性比較期間，若任一個其中的參數無法 hashable 時，則會引發一個 `TypeError` 例外。

typing.ClassVar

  特殊型別建構，用來標記類別變數。

  如同在 PEP 526 中的介紹，一個變數註解被包裝在 ClassVar 中時，會指出一個給定的屬性 (attribute) 意圖被當作類別變數使用，且不該被設定成該類別的實例。使用方法如下：

      class Starship:
          stats: ClassVar[dict[str, int]] = {} # 類別變數
          damage: int = 10                     # 實例變數

  `ClassVar` 只接受型別請不得使用下標。

  `ClassVar` 並不代表該類別本身，而且不應該和 `isinstance()` 或是 `issubclass()` 一起使用。`ClassVar` 不會改變 Python runtime 的行為，但它可以被第三方的型別檢查器使用。舉例來說，一個型別檢查器可能會標記下方的程式碼為一個錯誤：

      enterprise_d = Starship(3000)
      enterprise_d.stats = {} # Error, setting class variable on instance
      Starship.stats = {}     # This is OK

  在 3.5.3 版被加入.

  在 3.13 版的變更: `ClassVar` can now be nested in `Final` and vice versa.

typing.Final

  特殊型別建構，用來指出給型別檢查器的最終名稱。

  最終名稱不可以在任何作用域 (scope) 中重新賦值。在類別作用域中宣告的最終名稱，不得在子類別中進行覆寫 (override)。

  舉例來說：

      MAX_SIZE: Final = 9000
      MAX_SIZE += 1  # Error reported by type checker

      class Connection:
          TIMEOUT: Final[int] = 10

      class FastConnector(Connection):
          TIMEOUT = 1  # Error reported by type checker

  這些屬性 (property) 不會在 runtime 時進行檢查。更多詳細資訊請看 PEP 591。

  在 3.8 版被加入.

  在 3.13 版的變更: `Final` can now be nested in `ClassVar` and vice versa.

typing.Required

  特殊型別建構，用來標記一個 `TypedDict` 鍵值是必須的。

  主要用於 `total=False` 的 TypedDict。更多細節請見 `TypedDict` 與 PEP 655。

  在 3.11 版被加入.

typing.NotRequired

  特殊型別建構，用來標記一個 `TypedDict` 鍵值是可能消失的。

  更多細節請見 `TypedDict` 與 PEP 655。

  在 3.11 版被加入.

typing.ReadOnly

  特殊型別建構，用來標記一個 `TypedDict` 的項目是唯讀的。

  舉例來說：

      class Movie(TypedDict):
         title: ReadOnly[str]
         year: int

      def mutate_movie(m: Movie) -> None:
         m["year"] = 1999  # allowed
         m["title"] = "The Matrix"  # 型別檢查器錯誤

  這些屬性 (property) 不會在 runtime 時進行檢查。

  更多細節請見 `TypedDict` 與 PEP 705。

  在 3.13 版被加入.

typing.Annotated

  Special typing form to add context-specific metadata to an annotation.

  Add metadata `x` to a given type `T` by using the annotation `Annotated[T, x]`. Metadata added using `Annotated` can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a `__metadata__` attribute.

  If a library or tool encounters an annotation `Annotated[T, x]` and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as `T`. As such, `Annotated` can be useful for code that wants to use annotations for purposes outside Python's static typing system.

  Using `Annotated[T, x]` as an annotation still allows for static typechecking of `T`, as type checkers will simply ignore the metadata `x`. In this way, `Annotated` differs from the `@no_type_check` decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class.

  The responsibility of how to interpret the metadata lies with the tool or library encountering an `Annotated` annotation. A tool or library encountering an `Annotated` type can scan through the metadata elements to determine if they are of interest (e.g., using `isinstance()`).

  Annotated[<type>, <metadata>]

  Here is an example of how you might use `Annotated` to add metadata to type annotations if you were doing range analysis:

      @dataclass
      class ValueRange:
          lo: int
          hi: int

      T1 = Annotated[int, ValueRange(-10, 5)]
      T2 = Annotated[T1, ValueRange(-20, 3)]

  The first argument to `Annotated` must be a valid type. Multiple metadata elements can be supplied as `Annotated` supports variadic arguments. The order of the metadata elements is preserved and matters for equality checks:

      @dataclass
      class ctype:
           kind: str

      a1 = Annotated[int, ValueRange(3, 10), ctype("char")]
      a2 = Annotated[int, ctype("char"), ValueRange(3, 10)]

      assert a1 != a2  # 順序是有意義的

  It is up to the tool consuming the annotations to decide whether the client is allowed to add multiple metadata elements to one annotation and how to merge those annotations.

  Nested `Annotated` types are flattened. The order of the metadata elements starts with the innermost annotation:

      assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
          int, ValueRange(3, 10), ctype("char")
      ]

  However, this does not apply to `Annotated` types referenced through a type alias, to avoid forcing evaluation of the underlying `TypeAliasType`:

      type From3To10[T] = Annotated[T, ValueRange(3, 10)]
      assert Annotated[From3To10[int], ctype("char")] != Annotated[
         int, ValueRange(3, 10), ctype("char")
      ]

  Duplicated metadata elements are not removed:

      assert Annotated[int, ValueRange(3, 10)] != Annotated[
          int, ValueRange(3, 10), ValueRange(3, 10)
      ]

  `Annotated` can be used with nested and generic aliases:

  >     @dataclass
  >     class MaxLen:
  >         value: int

  >     type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]

  >     # When used in a type annotation, a type checker will treat "V" the same as
  >     # ``Annotated[list[tuple[int, int]], MaxLen(10)]``:
  >     type V = Vec[int]

  `Annotated` cannot be used with an unpacked `TypeVarTuple`:

      type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., Ann1]  # 無效

  where `T1`, `T2`, ... are `TypeVars`. This is invalid as only one type should be passed to Annotated.

  By default, `get_type_hints()` strips the metadata from annotations. Pass `include_extras=True` to have the metadata preserved:

  >     >>> from typing import Annotated, get_type_hints
  >     >>> def func(x: Annotated[int, "metadata"]) -> None: pass
  >     ...
  >     >>> get_type_hints(func)
  >     {'x': <class 'int'>, 'return': <class 'NoneType'>}
  >     >>> get_type_hints(func, include_extras=True)
  >     {'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>}

  At runtime, the metadata associated with an `Annotated` type can be retrieved via the `__metadata__` attribute:

  >     >>> from typing import Annotated
  >     >>> X = Annotated[int, "very", "important", "metadata"]
  >     >>> X
  >     typing.Annotated[int, 'very', 'important', 'metadata']
  >     >>> X.__metadata__
  >     ('very', 'important', 'metadata')

  If you want to retrieve the original type wrapped by `Annotated`, use the `__origin__` attribute:

  >     >>> from typing import Annotated, get_origin
  >     >>> Password = Annotated[str, "secret"]
  >     >>> Password.__origin__
  >     <class 'str'>

  Note that using `get_origin()` will return `Annotated` itself:

  >     >>> get_origin(Password)
  >     typing.Annotated

  也參考

  PEP 593 - Flexible function and variable annotations

    The PEP introducing `Annotated` to the standard library.

  在 3.9 版被加入.

typing.TypeIs

  Special typing construct for marking user-defined type predicate functions.

  `TypeIs` can be used to annotate the return type of a user-defined type predicate function. `TypeIs` only accepts a single type argument. At runtime, functions marked this way should return a boolean and take at least one positional argument.

  `TypeIs` aims to benefit type narrowing -- a technique used by static type checkers to determine a more precise type of an expression within a program's code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a "type predicate":

      def is_str(val: str | float):
          # "isinstance" type predicate
          if isinstance(val, str):
              # Type of ``val`` is narrowed to ``str``
              ...
          else:
              # Else, type of ``val`` is narrowed to ``float``.
              ...

  Sometimes it would be convenient to use a user-defined boolean function as a type predicate. Such a function should use `TypeIs[...]` or `TypeGuard` as its return type to alert static type checkers to this intention. `TypeIs` usually has more intuitive behavior than `TypeGuard`, but it cannot be used when the input and output types are incompatible (e.g., `list[object]` to `list[int]`) or when the function does not return `True` for all instances of the narrowed type.

  Using `-> TypeIs[NarrowedType]` tells the static type checker that for a given function:

  1. 回傳值是一個布林值。

  2. If the return value is `True`, the type of its argument is the intersection of the argument's original type and `NarrowedType`.

  3. If the return value is `False`, the type of its argument is narrowed to exclude `NarrowedType`.

  舉例來說：

      from typing import assert_type, final, TypeIs

      class Parent: pass
      class Child(Parent): pass
      @final
      class Unrelated: pass

      def is_parent(val: object) -> TypeIs[Parent]:
          return isinstance(val, Parent)

      def run(arg: Child | Unrelated):
          if is_parent(arg):
              # Type of ``arg`` is narrowed to the intersection
              # of ``Parent`` and ``Child``, which is equivalent to
              # ``Child``.
              assert_type(arg, Child)
          else:
              # Type of ``arg`` is narrowed to exclude ``Parent``,
              # so only ``Unrelated`` is left.
              assert_type(arg, Unrelated)

  The type inside `TypeIs` must be consistent with the type of the function's argument; if it is not, static type checkers will raise an error. An incorrectly written `TypeIs` function can lead to unsound behavior in the type system; it is the user's responsibility to write such functions in a type-safe manner.

  If a `TypeIs` function is a class or instance method, then the type in `TypeIs` maps to the type of the second parameter (after `cls` or `self`).

  In short, the form `def foo(arg: TypeA) -> TypeIs[TypeB]: ...`, means that if `foo(arg)` returns `True`, then `arg` is an instance of `TypeB`, and if it returns `False`, it is not an instance of `TypeB`.

  `TypeIs` also works with type variables. For more information, see PEP 742 (Narrowing types with `TypeIs`).

  在 3.13 版被加入.

typing.TypeGuard

  Special typing construct for marking user-defined type predicate functions.

  Type predicate functions are user-defined functions that return whether their argument is an instance of a particular type. `TypeGuard` works similarly to `TypeIs`, but has subtly different effects on type checking behavior (see below).

  Using `-> TypeGuard` tells the static type checker that for a given function:

  1. 回傳值是一個布林值。

  2. If the return value is `True`, the type of its argument is the type inside `TypeGuard`.

  `TypeGuard` also works with type variables. See PEP 647 for more details.

  舉例來說：

      def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
          '''Determines whether all objects in the list are strings'''
          return all(isinstance(x, str) for x in val)

      def func1(val: list[object]):
          if is_str_list(val):
              # Type of ``val`` is narrowed to ``list[str]``.
              print(" ".join(val))
          else:
              # Type of ``val`` remains as ``list[object]``.
              print("Not a list of strings!")

  `TypeIs` 和 `TypeGuard` 在以下幾個方面有所不同：

  - `TypeIs` requires the narrowed type to be a subtype of the input type, while `TypeGuard` does not. The main reason is to allow for things like narrowing `list[object]` to `list[str]` even though the latter is not a subtype of the former, since `list` is invariant.

  - When a `TypeGuard` function returns `True`, type checkers narrow the type of the variable to exactly the `TypeGuard` type. When a `TypeIs` function returns `True`, type checkers can infer a more precise type combining the previously known type of the variable with the `TypeIs` type. (Technically, this is known as an intersection type.)

  - When a `TypeGuard` function returns `False`, type checkers cannot narrow the type of the variable at all. When a `TypeIs` function returns `False`, type checkers can narrow the type of the variable to exclude the `TypeIs` type.

  在 3.10 版被加入.

typing.Unpack

  Typing operator to conceptually mark an object as having been unpacked.

  For example, using the unpack operator `*` on a type variable tuple is equivalent to using `Unpack` to mark the type variable tuple as having been unpacked:

      Ts = TypeVarTuple('Ts')
      tup: tuple[*Ts]
      # Effectively does:
      tup: tuple[Unpack[Ts]]

  In fact, `Unpack` can be used interchangeably with `*` in the context of `typing.TypeVarTuple` and `builtins.tuple` types. You might see `Unpack` being used explicitly in older versions of Python, where `*` couldn't be used in certain places:

      # In older versions of Python, TypeVarTuple and Unpack
      # are located in the `typing_extensions` backports package.
      from typing_extensions import TypeVarTuple, Unpack

      Ts = TypeVarTuple('Ts')
      tup: tuple[*Ts]         # Syntax error on Python <= 3.10!
      tup: tuple[Unpack[Ts]]  # Semantically equivalent, and backwards-compatible

  `Unpack` can also be used along with `typing.TypedDict` for typing `**kwargs` in a function signature:

      from typing import TypedDict, Unpack

      class Movie(TypedDict):
          name: str
          year: int

      # This function expects two keyword arguments - `name` of type `str`
      # and `year` of type `int`.
      def foo(**kwargs: Unpack[Movie]): ...

  See PEP 692 for more details on using `Unpack` for `**kwargs` typing.

  在 3.11 版被加入.

#### Building generic types and type aliases

The following classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating generic types and type aliases.

These objects can be created through special syntax (type parameter lists and the `type` statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.

class typing.Generic

  Abstract base class for generic types.

  A generic type is typically declared by adding a list of type parameters after the class name:

      class Mapping[KT, VT]:
          def __getitem__(self, key: KT) -> VT:
              ...
              # Etc.

  Such a class implicitly inherits from `Generic`. The runtime semantics of this syntax are discussed in the Language Reference.

  This class can then be used as follows:

      def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:
          try:
              return mapping[key]
          except KeyError:
              return default

  Here the brackets after the function name indicate a generic function.

  For backwards compatibility, generic classes can also be declared by explicitly inheriting from `Generic`. In this case, the type parameters must be declared separately:

      KT = TypeVar('KT')
      VT = TypeVar('VT')

      class Mapping(Generic[KT, VT]):
          def __getitem__(self, key: KT) -> VT:
              ...
              # Etc.

class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)

  Type variable.

  The preferred way to construct a type variable is via the dedicated syntax for generic functions, generic classes, and generic type aliases:

      class Sequence[T]:  # T 是一個 TypeVar
          ...

  This syntax can also be used to create bounded and constrained type variables:

      class StrSequence[S: str]:  # S is a TypeVar with a `str` upper bound;
          ...                     # we can say that S is "bounded by `str`"

      class StrOrBytesSequence[A: (str, bytes)]:  # A is a TypeVar constrained to str or bytes
          ...

  However, if desired, reusable type variables can also be constructed manually, like so:

      T = TypeVar('T')  # 可以是任何東西
      S = TypeVar('S', bound=str)  # 可以是任何 str 的子型別
      A = TypeVar('A', str, bytes)  # 必須是 str 或 bytes

  Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See `Generic` for more information on generic types. Generic functions work as follows:

      def repeat[T](x: T, n: int) -> Sequence[T]:
          """Return a list containing n references to x."""
          return [x]*n

      def print_capitalized[S: str](x: S) -> S:
          """Print x capitalized, and return x."""
          print(x.capitalize())
          return x

      def concatenate[A: (str, bytes)](x: A, y: A) -> A:
          """Add two strings or bytes objects together."""
          return x + y

  Note that type variables can be bounded, constrained, or neither, but cannot be both bounded and constrained.

  The variance of type variables is inferred by type checkers when they are created through the type parameter syntax or when `infer_variance=True` is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing `covariant=True` or `contravariant=True`. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

  Bounded type variables and constrained type variables have different semantics in several important ways. Using a bounded type variable means that the `TypeVar` will be solved using the most specific type possible:

      x = print_capitalized('a string')
      reveal_type(x)  # revealed type is str

      class StringSubclass(str):
          pass

      y = print_capitalized(StringSubclass('another string'))
      reveal_type(y)  # revealed type is StringSubclass

      z = print_capitalized(45)  # error: int is not a subtype of str

  The upper bound of a type variable can be a concrete type, abstract type (ABC or Protocol), or even a union of types:

      # Can be anything with an __abs__ method
      def print_abs[T: SupportsAbs](arg: T) -> None:
          print("Absolute value:", abs(arg))

      U = TypeVar('U', bound=str|bytes)  # Can be any subtype of the union str|bytes
      V = TypeVar('V', bound=SupportsAbs)  # Can be anything with an __abs__ method

  Using a constrained type variable, however, means that the `TypeVar` can only ever be solved as being exactly one of the constraints given:

      a = concatenate('one', 'two')
      reveal_type(a)  # revealed type is str

      b = concatenate(StringSubclass('one'), StringSubclass('two'))
      reveal_type(b)  # revealed type is str, despite StringSubclass being passed in

      c = concatenate('one', b'two')  # error: type variable 'A' can be either str or bytes in a function call, but not both

  在 runtime `isinstance(x, T)` 會引發 `TypeError`。

  __name__

    The name of the type variable.

  __covariant__

    Whether the type var has been explicitly marked as covariant.

  __contravariant__

    Whether the type var has been explicitly marked as contravariant.

  __infer_variance__

    Whether the type variable's variance should be inferred by type checkers.

    在 3.12 版被加入.

  __bound__

    The upper bound of the type variable, if any.

    在 3.12 版的變更: For type variables created through type parameter syntax, the bound is evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation).

  evaluate_bound()

    An evaluate function corresponding to the `__bound__` attribute. When called directly, this method supports only the `VALUE` format, which is equivalent to accessing the `__bound__` attribute directly, but the method object can be passed to `annotationlib.call_evaluate_function()` to evaluate the value in a different format.

    在 3.14 版被加入.

  __constraints__

    A tuple containing the constraints of the type variable, if any.

    在 3.12 版的變更: For type variables created through type parameter syntax, the constraints are evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation).

  evaluate_constraints()

    An evaluate function corresponding to the `__constraints__` attribute. When called directly, this method supports only the `VALUE` format, which is equivalent to accessing the `__constraints__` attribute directly, but the method object can be passed to `annotationlib.call_evaluate_function()` to evaluate the value in a different format.

    在 3.14 版被加入.

  __default__

    The default value of the type variable, or `typing.NoDefault` if it has no default.

    在 3.13 版被加入.

  evaluate_default()

    An evaluate function corresponding to the `__default__` attribute. When called directly, this method supports only the `VALUE` format, which is equivalent to accessing the `__default__` attribute directly, but the method object can be passed to `annotationlib.call_evaluate_function()` to evaluate the value in a different format.

    在 3.14 版被加入.

  has_default()

    Return whether or not the type variable has a default value. This is equivalent to checking whether `__default__` is not the `typing.NoDefault` singleton, except that it does not force evaluation of the lazily evaluated default value.

    在 3.13 版被加入.

  在 3.12 版的變更: Type variables can now be declared using the type parameter syntax introduced by PEP 695. The `infer_variance` parameter was added.

  在 3.13 版的變更: 新增對預設值的支援。

class typing.TypeVarTuple(name, *, default=typing.NoDefault)

  Type variable tuple. A specialized form of type variable that enables variadic generics.

  Type variable tuples can be declared in type parameter lists using a single asterisk (`*`) before the name:

      def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
          return (*tup[1:], tup[0])

  Or by explicitly invoking the `TypeVarTuple` constructor:

      T = TypeVar("T")
      Ts = TypeVarTuple("Ts")

      def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
          return (*tup[1:], tup[0])

  A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an arbitrary number of types by acting like an arbitrary number of type variables wrapped in a tuple. For example:

      # T is bound to int, Ts is bound to ()
      # Return value is (1,), which has type tuple[int]
      move_first_element_to_last(tup=(1,))

      # T is bound to int, Ts is bound to (str,)
      # Return value is ('spam', 1), which has type tuple[str, int]
      move_first_element_to_last(tup=(1, 'spam'))

      # T is bound to int, Ts is bound to (str, float)
      # Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
      move_first_element_to_last(tup=(1, 'spam', 3.0))

      # This fails to type check (and fails at runtime)
      # because tuple[()] is not compatible with tuple[T, *Ts]
      # (at least one element is required)
      move_first_element_to_last(tup=())

  Note the use of the unpacking operator `*` in `tuple[T, *Ts]`. Conceptually, you can think of `Ts` as a tuple of type variables `(T1, T2, ...)`. `tuple[T, *Ts]` would then become `tuple[T, *(T1, T2, ...)]`, which is equivalent to `tuple[T, T1, T2, ...]`. (Note that in older versions of Python, you might see this written using `Unpack` instead, as `Unpack[Ts]`.)

  Type variable tuples must always be unpacked. This helps distinguish type variable tuples from normal type variables:

      x: Ts          # 無效
      x: tuple[Ts]   # 無效
      x: tuple[*Ts]  # 正確的做法

  Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types:

      class Array[*Shape]:
          def __getitem__(self, key: tuple[*Shape]) -> float: ...
          def __abs__(self) -> "Array[*Shape]": ...
          def get_shape(self) -> tuple[*Shape]: ...

  Type variable tuples can be happily combined with normal type variables:

      class Array[DType, *Shape]:  # This is fine
          pass

      class Array2[*Shape, DType]:  # This would also be fine
          pass

      class Height: ...
      class Width: ...

      float_array_1d: Array[float, Height] = Array()     # Totally fine
      int_array_2d: Array[int, Height, Width] = Array()  # Yup, fine too

  However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters:

      x: tuple[*Ts, *Ts]            # 無效
      class Array[*Shape, *Shape]:  # 無效
          pass

  Finally, an unpacked type variable tuple can be used as the type annotation of `*args`:

      def call_soon[*Ts](
          callback: Callable[[*Ts], None],
          *args: *Ts
      ) -> None:
          ...
          callback(*args)

  In contrast to non-unpacked annotations of `*args` - e.g. `*args: int`, which would specify that all arguments are `int` - `*args: *Ts` enables reference to the types of the individual arguments in `*args`. Here, this allows us to ensure the types of the `*args` passed to `call_soon` match the types of the (positional) arguments of `callback`.

  See PEP 646 for more details on type variable tuples.

  __name__

    The name of the type variable tuple.

  __default__

    The default value of the type variable tuple, or `typing.NoDefault` if it has no default.

    在 3.13 版被加入.

  evaluate_default()

    An evaluate function corresponding to the `__default__` attribute. When called directly, this method supports only the `VALUE` format, which is equivalent to accessing the `__default__` attribute directly, but the method object can be passed to `annotationlib.call_evaluate_function()` to evaluate the value in a different format.

    在 3.14 版被加入.

  has_default()

    Return whether or not the type variable tuple has a default value. This is equivalent to checking whether `__default__` is not the `typing.NoDefault` singleton, except that it does not force evaluation of the lazily evaluated default value.

    在 3.13 版被加入.

  在 3.11 版被加入.

  在 3.12 版的變更: Type variable tuples can now be declared using the type parameter syntax introduced by PEP 695.

  在 3.13 版的變更: 新增對預設值的支援。

class typing.ParamSpec(name, *, bound=None, covariant=False, contravariant=False, default=typing.NoDefault)

  Parameter specification variable. A specialized version of type variables.

  In type parameter lists, parameter specifications can be declared with two asterisks (`**`):

      type IntFunc[**P] = Callable[P, int]

  For compatibility with Python 3.11 and earlier, `ParamSpec` objects can also be created as follows:

      P = ParamSpec('P')

  Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable -- a pattern commonly found in higher order functions and decorators. They are only valid when used in `Concatenate`, or as the first argument to `Callable`, or as parameters for user-defined Generics. See `Generic` for more information on generic types.

  For example, to add basic logging to a function, one can create a decorator `add_logging` to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:

      from collections.abc import Callable
      import logging

      def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:
          '''A type-safe decorator to add logging to a function.'''
          def inner(*args: P.args, **kwargs: P.kwargs) -> T:
              logging.info(f'{f.__name__} was called')
              return f(*args, **kwargs)
          return inner

      @add_logging
      def add_two(x: float, y: float) -> float:
          '''Add two numbers together.'''
          return x + y

  Without `ParamSpec`, the simplest way to annotate this previously was to use a `TypeVar` with upper bound `Callable[..., Any]`. However this causes two problems:

  1. The type checker can't type check the `inner` function because `*args` and `**kwargs` have to be typed `Any`.

  2. `cast()` may be required in the body of the `add_logging` decorator when returning the `inner` function, or the static type checker must be told to ignore the `return inner`.

  args
  kwargs

    Since `ParamSpec` captures both positional and keyword parameters, `P.args` and `P.kwargs` can be used to split a `ParamSpec` into its components. `P.args` represents the tuple of positional parameters in a given call and should only be used to annotate `*args`. `P.kwargs` represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate `**kwargs`. Both attributes require the annotated parameter to be in scope. At runtime, `P.args` and `P.kwargs` are instances respectively of `ParamSpecArgs` and `ParamSpecKwargs`.

  __name__

    The name of the parameter specification.

  __default__

    The default value of the parameter specification, or `typing.NoDefault` if it has no default.

    在 3.13 版被加入.

  evaluate_default()

    An evaluate function corresponding to the `__default__` attribute. When called directly, this method supports only the `VALUE` format, which is equivalent to accessing the `__default__` attribute directly, but the method object can be passed to `annotationlib.call_evaluate_function()` to evaluate the value in a different format.

    在 3.14 版被加入.

  has_default()

    Return whether or not the parameter specification has a default value. This is equivalent to checking whether `__default__` is not the `typing.NoDefault` singleton, except that it does not force evaluation of the lazily evaluated default value.

    在 3.13 版被加入.

  Parameter specification variables created with `covariant=True` or `contravariant=True` can be used to declare covariant or contravariant generic types. The `bound` argument is also accepted, similar to `TypeVar`. However the actual semantics of these keywords are yet to be decided.

  在 3.10 版被加入.

  在 3.12 版的變更: Parameter specifications can now be declared using the type parameter syntax introduced by PEP 695.

  在 3.13 版的變更: 新增對預設值的支援。

  備註

  Only parameter specification variables defined in global scope can be pickled.

  也參考

  - PEP 612 -- 參數技術規範變數

  - `Concatenate`

  - 註釋 callable 物件

typing.ParamSpecArgs
typing.ParamSpecKwargs

  Arguments and keyword arguments attributes of a `ParamSpec`. The `P.args` attribute of a `ParamSpec` is an instance of `ParamSpecArgs`, and `P.kwargs` is an instance of `ParamSpecKwargs`. They are intended for runtime introspection and have no special meaning to static type checkers.

  Calling `get_origin()` on either of these objects will return the original `ParamSpec`:

      >>> from typing import ParamSpec, get_origin
      >>> P = ParamSpec("P")
      >>> get_origin(P.args) is P
      True
      >>> get_origin(P.kwargs) is P
      True

  在 3.10 版被加入.

class typing.TypeAliasType(name, value, *, type_params=())

  The type of type aliases created through the `type` statement.

  舉例來說：

      >>> type Alias = int
      >>> type(Alias)
      <class 'typing.TypeAliasType'>

  在 3.12 版被加入.

  __name__

    The name of the type alias:

        >>> type Alias = int
        >>> Alias.__name__
        'Alias'

  __module__

    The name of the module in which the type alias was defined:

        >>> type Alias = int
        >>> Alias.__module__
        '__main__'

  __type_params__

    The type parameters of the type alias, or an empty tuple if the alias is not generic:

        >>> type ListOrSet[T] = list[T] | set[T]
        >>> ListOrSet.__type_params__
        (T,)
        >>> type NotGeneric = int
        >>> NotGeneric.__type_params__
        ()

  __value__

    The type alias's value. This is lazily evaluated, so names used in the definition of the alias are not resolved until the `__value__` attribute is accessed:

        >>> type Mutually = Recursive
        >>> type Recursive = Mutually
        >>> Mutually
        Mutually
        >>> Recursive
        Recursive
        >>> Mutually.__value__
        Recursive
        >>> Recursive.__value__
        Mutually

  evaluate_value()

    An evaluate function corresponding to the `__value__` attribute. When called directly, this method supports only the `VALUE` format, which is equivalent to accessing the `__value__` attribute directly, but the method object can be passed to `annotationlib.call_evaluate_function()` to evaluate the value in a different format:

        >>> type Alias = undefined
        >>> Alias.__value__
        Traceback (most recent call last):
        ...
        NameError: name 'undefined' is not defined
        >>> from annotationlib import Format, call_evaluate_function
        >>> Alias.evaluate_value(Format.VALUE)
        Traceback (most recent call last):
        ...
        NameError: name 'undefined' is not defined
        >>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF)
        ForwardRef('undefined')

    在 3.14 版被加入.

  Unpacking

  Type aliases support star unpacking using the `*Alias` syntax. This is equivalent to using `Unpack[Alias]` directly:

      >>> type Alias = tuple[int, str]
      >>> type Unpacked = tuple[bool, *Alias]
      >>> Unpacked.__value__
      tuple[bool, typing.Unpack[Alias]]

  在 3.14 版被加入.

#### Other special directives

These functions and classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating and declaring types.

class typing.NamedTuple

  Typed version of `collections.namedtuple()`.

  用法：

      class Employee(NamedTuple):
          name: str
          id: int

  這等價於：

      Employee = collections.namedtuple('Employee', ['name', 'id'])

  To give a field a default value, you can assign to it in the class body:

      class Employee(NamedTuple):
          name: str
          id: int = 3

      employee = Employee('Guido')
      assert employee.id == 3

  Fields with a default value must come after any fields without a default.

  The resulting class has an extra attribute `__annotations__` giving a dict that maps the field names to the field types. (The field names are in the `_fields` attribute and the default values are in the `_field_defaults` attribute, both of which are part of the `namedtuple()` API.)

  `NamedTuple` subclasses can also have docstrings and methods:

      class Employee(NamedTuple):
          """Represents an employee."""
          name: str
          id: int = 3

          def __repr__(self) -> str:
              return f'<Employee {self.name}, id={self.id}>'

  `NamedTuple` subclasses can be generic:

      class Group[T](NamedTuple):
          key: T
          group: list[T]

  Backward-compatible usage:

      # For creating a generic NamedTuple on Python 3.11
      T = TypeVar("T")

      class Group(NamedTuple, Generic[T]):
          key: T
          group: list[T]

      # A functional syntax is also supported
      Employee = NamedTuple('Employee', [('name', str), ('id', int)])

  在 3.6 版的變更: Added support for PEP 526 variable annotation syntax.

  在 3.6.1 版的變更: Added support for default values, methods, and docstrings.

  在 3.8 版的變更: The `_field_types` and `__annotations__` attributes are now regular dictionaries instead of instances of `OrderedDict`.

  在 3.9 版的變更: Removed the `_field_types` attribute in favor of the more standard `__annotations__` attribute which has the same information.

  在 3.9 版的變更: `NamedTuple` is now a function rather than a class. It can still be used as a class base, as described above.

  在 3.11 版的變更: Added support for generic namedtuples.

  在 3.14 版的變更: Using `super()` (and the `__class__` closure variable) in methods of `NamedTuple` subclasses is unsupported and causes a `TypeError`.

  自從版本 3.13 後不推薦使用，將會自版本 3.15 中移除。: The undocumented keyword argument syntax for creating NamedTuple classes (`NT = NamedTuple("NT", x=int)`) is deprecated, and will be disallowed in 3.15. Use the class-based syntax or the functional syntax instead.

  自從版本 3.13 後不推薦使用，將會自版本 3.15 中移除。: When using the functional syntax to create a NamedTuple class, failing to pass a value to the 'fields' parameter (`NT = NamedTuple("NT")`) is deprecated. Passing `None` to the 'fields' parameter (`NT = NamedTuple("NT", None)`) is also deprecated. Both will be disallowed in Python 3.15. To create a NamedTuple class with 0 fields, use `class NT(NamedTuple): pass` or `NT = NamedTuple("NT", [])`.

class typing.NewType(name, tp)

  Helper class to create low-overhead distinct types.

  A `NewType` is considered a distinct type by a typechecker. At runtime, however, calling a `NewType` returns its argument unchanged.

  用法：

      UserId = NewType('UserId', int)  # Declare the NewType "UserId"
      first_user = UserId(1)  # "UserId" returns the argument unchanged at runtime

  __module__

    The name of the module in which the new type is defined.

  __name__

    The name of the new type.

  __supertype__

    The type that the new type is based on.

  在 3.5.2 版被加入.

  在 3.10 版的變更: `NewType` is now a class rather than a function.

class typing.Protocol(Generic)

  Base class for protocol classes.

  Protocol classes are defined like this:

      class Proto(Protocol):
          def meth(self) -> int:
              ...

  Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:

      class C:
          def meth(self) -> int:
              return 0

      def func(x: Proto) -> int:
          return x.meth()

      func(C())  # Passes static type check

  See PEP 544 for more details. Protocol classes decorated with `runtime_checkable()` (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes without this decorator cannot be used as the second argument to `isinstance()` or `issubclass()`.

  Protocol classes can be generic, for example:

      class GenProto[T](Protocol):
          def meth(self) -> T:
              ...

  In code that needs to be compatible with Python 3.11 or older, generic Protocols can be written as follows:

      T = TypeVar("T")

      class GenProto(Protocol[T]):
          def meth(self) -> T:
              ...

  在 3.8 版被加入.

@typing.runtime_checkable

  Mark a protocol class as a runtime protocol.

  Such a protocol can be used with `isinstance()` and `issubclass()`. This allows a simple-minded structural check, very similar to "one trick ponies" in `collections.abc` such as `Iterable`. For example:

      @runtime_checkable
      class Closable(Protocol):
          def close(self): ...

      assert isinstance(open('/some/file'), Closable)

      @runtime_checkable
      class Named(Protocol):
          name: str

      import threading
      assert isinstance(threading.Thread(name='Bob'), Named)

  This decorator raises `TypeError` when applied to a non-protocol class.

  備註

  `runtime_checkable()` will check only the presence of the required methods or attributes, not their type signatures or types. For example, `ssl.SSLObject` is a class, therefore it passes an `issubclass()` check against Callable. However, the `ssl.SSLObject.__init__` method exists only to raise a `TypeError` with a more informative message, therefore making it impossible to call (instantiate) `ssl.SSLObject`.

  備註

  An `isinstance()` check against a runtime-checkable protocol can be surprisingly slow compared to an `isinstance()` check against a non-protocol class. Consider using alternative idioms such as `hasattr()` calls for structural checks in performance-sensitive code.

  在 3.8 版被加入.

  在 3.12 版的變更: The internal implementation of `isinstance()` checks against runtime-checkable protocols now uses `inspect.getattr_static()` to look up attributes (previously, `hasattr()` was used). As a result, some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change.

  在 3.12 版的變更: The members of a runtime-checkable protocol are now considered "frozen" at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on `isinstance()` checks comparing objects to the protocol. See What's new in Python 3.12 for more details.

class typing.TypedDict(dict)

  Special construct to add type hints to a dictionary. At runtime "`TypedDict` instances" are simply `dicts`.

  `TypedDict` declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

      class Point2D(TypedDict):
          x: int
          y: int
          label: str

      a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
      b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check

      assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

  An alternative way to create a `TypedDict` is by using function-call syntax. The second argument must be a literal `dict`:

      Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

  This functional syntax allows defining keys which are not valid identifiers, for example because they are keywords or contain hyphens, or when key names must not be mangled like regular private names:

      # raises SyntaxError
      class Point2D(TypedDict):
          in: int  # 'in' is a keyword
          x-y: int  # name with hyphens

      class Definition(TypedDict):
          __schema: str  # mangled to `_Definition__schema`

      # OK, functional syntax
      Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
      Definition = TypedDict('Definition', {'__schema': str})  # not mangled

  By default, all keys must be present in a `TypedDict`. It is possible to mark individual keys as non-required using `NotRequired`:

      class Point2D(TypedDict):
          x: int
          y: int
          label: NotRequired[str]

      # 替代語法
      Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]})

  This means that a `Point2D` `TypedDict` can have the `label` key omitted.

  It is also possible to mark all keys as non-required by default by specifying a totality of `False`:

      class Point2D(TypedDict, total=False):
          x: int
          y: int

      # 替代語法
      Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)

  This means that a `Point2D` `TypedDict` can have any of the keys omitted. A type checker is only expected to support a literal `False` or `True` as the value of the `total` argument. `True` is the default, and makes all items defined in the class body required.

  Individual keys of a `total=False` `TypedDict` can be marked as required using `Required`:

      class Point2D(TypedDict, total=False):
          x: Required[int]
          y: Required[int]
          label: str

      # 替代語法
      Point2D = TypedDict('Point2D', {
          'x': Required[int],
          'y': Required[int],
          'label': str
      }, total=False)

  It is possible for a `TypedDict` type to inherit from one or more other `TypedDict` types using the class-based syntax. Usage:

      class Point3D(Point2D):
          z: int

  `Point3D` has three items: `x`, `y` and `z`. It is equivalent to this definition:

      class Point3D(TypedDict):
          x: int
          y: int
          z: int

  A `TypedDict` cannot inherit from a non-`TypedDict` class, except for `Generic`. For example:

      class X(TypedDict):
          x: int

      class Y(TypedDict):
          y: int

      class Z(object): pass  # 一個非 TypedDict 的類別

      class XY(X, Y): pass  # OK

      class XZ(X, Z): pass  # 引發 TypeError

  A `TypedDict` can be generic:

      class Group[T](TypedDict):
          key: T
          group: list[T]

  To create a generic `TypedDict` that is compatible with Python 3.11 or lower, inherit from `Generic` explicitly:

      T = TypeVar("T")

      class Group(TypedDict, Generic[T]):
          key: T
          group: list[T]

  A `TypedDict` can be introspected via annotations dicts (see 註釋 (annotation) 最佳實踐 for more information on annotations best practices), `__total__`, `__required_keys__`, and `__optional_keys__`.

  __total__

    `Point2D.__total__` gives the value of the `total` argument. Example:

        >>> from typing import TypedDict
        >>> class Point2D(TypedDict): pass
        >>> Point2D.__total__
        True
        >>> class Point2D(TypedDict, total=False): pass
        >>> Point2D.__total__
        False
        >>> class Point3D(Point2D): pass
        >>> Point3D.__total__
        True

    This attribute reflects only the value of the `total` argument to the current `TypedDict` class, not whether the class is semantically total. For example, a `TypedDict` with `__total__` set to `True` may have keys marked with `NotRequired`, or it may inherit from another `TypedDict` with `total=False`. Therefore, it is generally better to use `__required_keys__` and `__optional_keys__` for introspection.

  __required_keys__

    在 3.9 版被加入.

  __optional_keys__

    `Point2D.__required_keys__` and `Point2D.__optional_keys__` return `frozenset` objects containing required and non-required keys, respectively.

    Keys marked with `Required` will always appear in `__required_keys__` and keys marked with `NotRequired` will always appear in `__optional_keys__`.

    For backwards compatibility with Python 3.10 and below, it is also possible to use inheritance to declare both required and non-required keys in the same `TypedDict` . This is done by declaring a `TypedDict` with one value for the `total` argument and then inheriting from it in another `TypedDict` with a different value for `total`:

        >>> class Point2D(TypedDict, total=False):
        ...     x: int
        ...     y: int
        ...
        >>> class Point3D(Point2D):
        ...     z: int
        ...
        >>> Point3D.__required_keys__ == frozenset({'z'})
        True
        >>> Point3D.__optional_keys__ == frozenset({'x', 'y'})
        True

    在 3.9 版被加入.

    備註

    If `from __future__ import annotations` is used or if annotations are given as strings, annotations are not evaluated when the `TypedDict` is defined. Therefore, the runtime introspection that `__required_keys__` and `__optional_keys__` rely on may not work properly, and the values of the attributes may be incorrect.

  Support for `ReadOnly` is reflected in the following attributes:

  __readonly_keys__

    A `frozenset` containing the names of all read-only keys. Keys are read-only if they carry the `ReadOnly` qualifier.

    在 3.13 版被加入.

  __mutable_keys__

    A `frozenset` containing the names of all mutable keys. Keys are mutable if they do not carry the `ReadOnly` qualifier.

    在 3.13 版被加入.

  See the TypedDict section in the typing documentation for more examples and detailed rules.

  在 3.8 版被加入.

  在 3.9 版的變更: `TypedDict` is now a function rather than a class. It can still be used as a class base, as described above.

  在 3.11 版的變更: Added support for marking individual keys as `Required` or `NotRequired`. See PEP 655.

  在 3.11 版的變更: Added support for generic `TypedDict`s.

  在 3.13 版的變更: Removed support for the keyword-argument method of creating `TypedDict`s.

  在 3.13 版的變更: Support for the `ReadOnly` qualifier was added.

  自從版本 3.13 後不推薦使用，將會自版本 3.15 中移除。: When using the functional syntax to create a TypedDict class, failing to pass a value to the 'fields' parameter (`TD = TypedDict("TD")`) is deprecated. Passing `None` to the 'fields' parameter (`TD = TypedDict("TD", None)`) is also deprecated. Both will be disallowed in Python 3.15. To create a TypedDict class with 0 fields, use `class TD(TypedDict): pass` or `TD = TypedDict("TD", {})`.

### 協定

The following protocols are provided by the `typing` module. All are decorated with `@runtime_checkable`.

class typing.SupportsAbs

  An ABC with one abstract method `__abs__` that is covariant in its return type.

class typing.SupportsBytes

  一個有抽象方法 `__bytes__` 的 ABC。

class typing.SupportsComplex

  一個有抽象方法 `__complex__` 的 ABC。

class typing.SupportsFloat

  一個有抽象方法 `__float__` 的 ABC。

class typing.SupportsIndex

  一個有抽象方法 `__index__` 的 ABC。

  在 3.8 版被加入.

class typing.SupportsInt

  一個有抽象方法 `__int__` 的 ABC。

class typing.SupportsRound

  An ABC with one abstract method `__round__` that is covariant in its return type.

### ABCs and Protocols for working with I/O

class typing.IO[AnyStr]
class typing.TextIO
class typing.BinaryIO

  Generic class `IO[AnyStr]` and its subclasses `TextIO(IO[str])` and `BinaryIO(IO[bytes])` represent the types of I/O streams such as returned by `open()`. Please note that these classes are not protocols, and their interface is fairly broad.

The protocols `io.Reader` and `io.Writer` offer a simpler alternative for argument types, when only the `read()` or `write()` methods are accessed, respectively:

    def read_and_write(reader: Reader[str], writer: Writer[bytes]):
        data = reader.read()
        writer.write(data.encode())

Also consider using `collections.abc.Iterable` for iterating over the lines of an input stream:

    def read_config(stream: Iterable[str]):
        for line in stream:
            ...

### 函式與裝飾器

typing.cast(typ, val)

  Cast a value to a type.

  This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible).

typing.assert_type(val, typ, /)

  Ask a static type checker to confirm that val has an inferred type of typ.

  At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument.

  When a static type checker encounters a call to `assert_type()`, it emits an error if the value is not of the specified type:

      def greet(name: str) -> None:
          assert_type(name, str)  # OK，推斷出的 `name` 型別是 `str`
          assert_type(name, int)  # 型別檢查器錯誤

  This function is useful for ensuring the type checker's understanding of a script is in line with the developer's intentions:

      def complex_function(arg: object):
          # Do some complex type-narrowing logic,
          # after which we hope the inferred type will be `int`
          ...
          # Test whether the type checker correctly understands our function
          assert_type(arg, int)

  在 3.11 版被加入.

typing.assert_never(arg, /)

  Ask a static type checker to confirm that a line of code is unreachable.

  舉例來說：

      def int_or_str(arg: int | str) -> None:
          match arg:
              case int():
                  print("It's an int")
              case str():
                  print("It's a str")
              case _ as unreachable:
                  assert_never(unreachable)

  Here, the annotations allow the type checker to infer that the last case can never execute, because `arg` is either an `int` or a `str`, and both options are covered by earlier cases.

  If a type checker finds that a call to `assert_never()` is reachable, it will emit an error. For example, if the type annotation for `arg` was instead `int | str | float`, the type checker would emit an error pointing out that `unreachable` is of type `float`. For a call to `assert_never` to pass type checking, the inferred type of the argument passed in must be the bottom type, `Never`, and nothing else.

  At runtime, this throws an exception when called.

  也參考

  Unreachable Code and Exhaustiveness Checking has more information about exhaustiveness checking with static typing.

  在 3.11 版被加入.

typing.reveal_type(obj, /)

  Ask a static type checker to reveal the inferred type of an expression.

  When a static type checker encounters a call to this function, it emits a diagnostic with the inferred type of the argument. For example:

      x: int = 1
      reveal_type(x)  # Revealed type is "builtins.int"

  This can be useful when you want to debug how your type checker handles a particular piece of code.

  At runtime, this function prints the runtime type of its argument to `sys.stderr` and returns the argument unchanged (allowing the call to be used within an expression):

      x = reveal_type(1)  # 印出 "Runtime type is int"
      print(x)  # 印出 "1"

  Note that the runtime type may be different from (more or less specific than) the type statically inferred by a type checker.

  Most type checkers support `reveal_type()` anywhere, even if the name is not imported from `typing`. Importing the name from `typing`, however, allows your code to run without runtime errors and communicates intent more clearly.

  在 3.11 版被加入.

@typing.dataclass_transform(*, eq_default=True, order_default=False, kw_only_default=False, frozen_default=False, field_specifiers=(), **kwargs)

  Decorator to mark an object as providing `dataclass`-like behavior.

  `dataclass_transform` may be used to decorate a class, metaclass, or a function that is itself a decorator. The presence of `@dataclass_transform()` tells a static type checker that the decorated object performs runtime "magic" that transforms a class in a similar way to `@dataclasses.dataclass`.

  Example usage with a decorator function:

      @dataclass_transform()
      def create_model[T](cls: type[T]) -> type[T]:
          ...
          return cls

      @create_model
      class CustomerModel:
          id: int
          name: str

  On a base class:

      @dataclass_transform()
      class ModelBase: ...

      class CustomerModel(ModelBase):
          id: int
          name: str

  On a metaclass:

      @dataclass_transform()
      class ModelMeta(type): ...

      class ModelBase(metaclass=ModelMeta): ...

      class CustomerModel(ModelBase):
          id: int
          name: str

  The `CustomerModel` classes defined above will be treated by type checkers similarly to classes created with `@dataclasses.dataclass`. For example, type checkers will assume these classes have `__init__` methods that accept `id` and `name`.

  The decorated class, metaclass, or function may accept the following bool arguments which type checkers will assume have the same effect as they would have on the `@dataclasses.dataclass` decorator: `init`, `eq`, `order`, `unsafe_hash`, `frozen`, `match_args`, `kw_only`, and `slots`. It must be possible for the value of these arguments (`True` or `False`) to be statically evaluated.

  The arguments to the `dataclass_transform` decorator can be used to customize the default behaviors of the decorated class, metaclass, or function:

  參數:

    - eq_default (bool) -- Indicates whether the `eq` parameter is assumed to be `True` or `False` if it is omitted by the caller. Defaults to `True`.

    - order_default (bool) -- Indicates whether the `order` parameter is assumed to be `True` or `False` if it is omitted by the caller. Defaults to `False`.

    - kw_only_default (bool) -- Indicates whether the `kw_only` parameter is assumed to be `True` or `False` if it is omitted by the caller. Defaults to `False`.

    - frozen_default (bool) --

      Indicates whether the `frozen` parameter is assumed to be `True` or `False` if it is omitted by the caller. Defaults to `False`.

      在 3.12 版被加入.

    - field_specifiers (tuple[Callable[..., Any], ...]) -- Specifies a static list of supported classes or functions that describe fields, similar to `dataclasses.field()`. Defaults to `()`.

    - **kwargs (Any) -- Arbitrary other keyword arguments are accepted in order to allow for possible future extensions.

  Type checkers recognize the following optional parameters on field specifiers:

  Recognised parameters for field specifiers
  Parameter name | Description
  --- | ---
  `init` | Indicates whether the field should be included in the synthesized `__init__` method. If unspecified, `init` defaults to `True`.
  `default` | Provides the default value for the field.
  `default_factory` | Provides a runtime callback that returns the default value for the field. If neither `default` nor `default_factory` are specified, the field is assumed to have no default value and must be provided a value when the class is instantiated.
  `factory` | An alias for the `default_factory` parameter on field specifiers.
  `kw_only` | Indicates whether the field should be marked as keyword-only. If `True`, the field will be keyword-only. If `False`, it will not be keyword-only. If unspecified, the value of the `kw_only` parameter on the object decorated with `dataclass_transform` will be used, or if that is unspecified, the value of `kw_only_default` on `dataclass_transform` will be used.
  `alias` | Provides an alternative name for the field. This alternative name is used in the synthesized `__init__` method.

  At runtime, this decorator records its arguments in the `__dataclass_transform__` attribute on the decorated object. It has no other runtime effect.

  更多細節請見 PEP 681。

  在 3.11 版被加入.

@typing.overload

  Decorator for creating overloaded functions and methods.

  The `@overload` decorator allows describing functions and methods that support multiple different combinations of argument types. A series of `@overload`-decorated definitions must be followed by exactly one non-`@overload`-decorated definition (for the same function/method).

  `@overload`-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-`@overload`-decorated definition. The non-`@overload`-decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling an `@overload`-decorated function directly will raise `NotImplementedError`.

  An example of overload that gives a more precise type than can be expressed using a union or a type variable:

      @overload
      def process(response: None) -> None:
          ...
      @overload
      def process(response: int) -> tuple[int, str]:
          ...
      @overload
      def process(response: bytes) -> str:
          ...
      def process(response):
          ...  # 實際的實作在這邊

  See PEP 484 for more details and comparison with other typing semantics.

  在 3.11 版的變更: Overloaded functions can now be introspected at runtime using `get_overloads()`.

typing.get_overloads(func)

  Return a sequence of `@overload`-decorated definitions for func.

  func is the function object for the implementation of the overloaded function. For example, given the definition of `process` in the documentation for `@overload`, `get_overloads(process)` will return a sequence of three function objects for the three defined overloads. If called on a function with no overloads, `get_overloads()` returns an empty sequence.

  `get_overloads()` can be used for introspecting an overloaded function at runtime.

  在 3.11 版被加入.

typing.clear_overloads()

  Clear all registered overloads in the internal registry.

  This can be used to reclaim the memory used by the registry.

  在 3.11 版被加入.

@typing.final

  Decorator to indicate final methods and final classes.

  Decorating a method with `@final` indicates to a type checker that the method cannot be overridden in a subclass. Decorating a class with `@final` indicates that it cannot be subclassed.

  舉例來說：

      class Base:
          @final
          def done(self) -> None:
              ...
      class Sub(Base):
          def done(self) -> None:  # 型別檢查器回報的錯誤
              ...

      @final
      class Leaf:
          ...
      class Other(Leaf):  # 型別檢查器回報的錯誤
          ...

  這些屬性 (property) 不會在 runtime 時進行檢查。更多詳細資訊請看 PEP 591。

  在 3.8 版被加入.

  在 3.11 版的變更: The decorator will now attempt to set a `__final__` attribute to `True` on the decorated object. Thus, a check like `if getattr(obj, "__final__", False)` can be used at runtime to determine whether an object `obj` has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

@typing.no_type_check

  Decorator to indicate that annotations are not type hints.

  This works as a class or function decorator. With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). Type checkers will ignore all annotations in a function or class with this decorator.

  `@no_type_check` mutates the decorated object in place.

@typing.no_type_check_decorator

  Decorator to give another decorator the `no_type_check()` effect.

  This wraps the decorator with something that wraps the decorated function in `no_type_check()`.

  自從版本 3.13 後不推薦使用，將會自版本 3.15 中移除。: No type checker ever added support for `@no_type_check_decorator`. It is therefore deprecated, and will be removed in Python 3.15.

@typing.override

  Decorator to indicate that a method in a subclass is intended to override a method or attribute in a superclass.

  Type checkers should emit an error if a method decorated with `@override` does not, in fact, override anything. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class.

  舉例來說：

      class Base:
          def log_status(self) -> None:
              ...

      class Sub(Base):
          @override
          def log_status(self) -> None:  # Okay: overrides Base.log_status
              ...

          @override
          def done(self) -> None:  # Error reported by type checker
              ...

  There is no runtime checking of this property.

  The decorator will attempt to set an `__override__` attribute to `True` on the decorated object. Thus, a check like `if getattr(obj, "__override__", False)` can be used at runtime to determine whether an object `obj` has been marked as an override. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

  更多細節請見 PEP 698。

  在 3.12 版被加入.

@typing.type_check_only

  Decorator to mark a class or function as unavailable at runtime.

  This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:

      @type_check_only
      class Response:  # private or not available at runtime
          code: int
          def get_header(self, name: str) -> str: ...

      def fetch_response() -> Response: ...

  Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.

### Introspection helpers

typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False)

  Return a dictionary containing type hints for a function, method, module or class object.

  This is often the same as `obj.__annotations__`, but this function makes the following changes to the annotations dictionary:

  - Forward references encoded as string literals or `ForwardRef` objects are handled by evaluating them in globalns, localns, and (where applicable) obj's type parameter namespace. If globalns or localns is not given, appropriate namespace dictionaries are inferred from obj.

  - `None` is replaced with `types.NoneType`.

  - If `@no_type_check` has been applied to obj, an empty dictionary is returned.

  - If obj is a class `C`, the function returns a dictionary that merges annotations from `C`'s base classes with those on `C` directly. This is done by traversing `C.__mro__` and iteratively combining `__annotations__` dictionaries. Annotations on classes appearing earlier in the method resolution order always take precedence over annotations on classes appearing later in the method resolution order.

  - The function recursively replaces all occurrences of `Annotated[T, ...]`, `Required[T]`, `NotRequired[T]`, and `ReadOnly[T]` with `T`, unless include_extras is set to `True` (see `Annotated` for more information).

  See also `annotationlib.get_annotations()`, a lower-level function that returns annotations more directly.

  警示

  This function may execute arbitrary code contained in annotations. See Security implications of introspecting annotations for more information.

  備註

  If any forward references in the annotations of obj are not resolvable or are not valid Python code, this function will raise an exception such as `NameError`. For example, this can happen with imported type aliases that include forward references, or with names imported under `if TYPE_CHECKING`.

  在 3.9 版的變更: 新增 `include_extras` 參數（如 PEP 593 中所述）。更多資訊請見 `Annotated` 的文件。

  在 3.11 版的變更: Previously, `Optional[t]` was added for function and method annotations if a default value equal to `None` was set. Now the annotation is returned unchanged.

typing.get_origin(tp)

  Get the unsubscripted version of a type: for a typing object of the form `X[Y, Z, ...]` return `X`.

  If `X` is a typing-module alias for a builtin or `collections` class, it will be normalized to the original class. If `X` is an instance of `ParamSpecArgs` or `ParamSpecKwargs`, return the underlying `ParamSpec`. Return `None` for unsupported objects.

  舉例：

      assert get_origin(str) is None
      assert get_origin(Dict[str, int]) is dict
      assert get_origin(Union[int, str]) is Union
      assert get_origin(Annotated[str, "metadata"]) is Annotated
      P = ParamSpec('P')
      assert get_origin(P.args) is P
      assert get_origin(P.kwargs) is P

  在 3.8 版被加入.

typing.get_args(tp)

  Get type arguments with all substitutions performed: for a typing object of the form `X[Y, Z, ...]` return `(Y, Z, ...)`.

  If `X` is a union or `Literal` contained in another generic type, the order of `(Y, Z, ...)` may be different from the order of the original arguments `[Y, Z, ...]` due to type caching. Return `()` for unsupported objects.

  舉例：

      assert get_args(int) == ()
      assert get_args(Dict[int, str]) == (int, str)
      assert get_args(Union[int, str]) == (int, str)

  在 3.8 版被加入.

typing.get_protocol_members(tp)

  Return the set of members defined in a `Protocol`.

      >>> from typing import Protocol, get_protocol_members
      >>> class P(Protocol):
      ...     def a(self) -> str: ...
      ...     b: int
      >>> get_protocol_members(P) == frozenset({'a', 'b'})
      True

  Raise `TypeError` for arguments that are not Protocols.

  在 3.13 版被加入.

typing.is_protocol(tp)

  確定一個型別是否 `Protocol`。

  舉例來說：

      class P(Protocol):
          def a(self) -> str: ...
          b: int

      is_protocol(P)    # => True
      is_protocol(int)  # => False

  在 3.13 版被加入.

typing.is_typeddict(tp)

  Check if a type is a `TypedDict`.

  舉例來說：

      class Film(TypedDict):
          title: str
          year: int

      assert is_typeddict(Film)
      assert not is_typeddict(list | str)

      # TypedDict is a factory for creating typed dicts,
      # not a typed dict itself
      assert not is_typeddict(TypedDict)

  在 3.10 版被加入.

class typing.ForwardRef

  Class used for internal typing representation of string forward references.

  For example, `List["SomeClass"]` is implicitly transformed into `List[ForwardRef("SomeClass")]`. `ForwardRef` should not be instantiated by a user, but may be used by introspection tools.

  備註

  PEP 585 generic types such as `list["SomeClass"]` will not be implicitly transformed into `list[ForwardRef("SomeClass")]` and thus will not automatically resolve to `list[SomeClass]`.

  在 3.7.4 版被加入.

  在 3.14 版的變更: This is now an alias for `annotationlib.ForwardRef`. Several undocumented behaviors of this class have been changed; for example, after a `ForwardRef` has been evaluated, the evaluated value is no longer cached.

typing.evaluate_forward_ref(forward_ref, *, owner=None, globals=None, locals=None, type_params=None, format=annotationlib.Format.VALUE)

  Evaluate an `annotationlib.ForwardRef` as a type hint.

  This is similar to calling `annotationlib.ForwardRef.evaluate()`, but unlike that method, `evaluate_forward_ref()` also recursively evaluates forward references nested within the type hint.

  See the documentation for `annotationlib.ForwardRef.evaluate()` for the meaning of the owner, globals, locals, type_params, and format parameters.

  警示

  This function may execute arbitrary code contained in annotations. See Security implications of introspecting annotations for more information.

  在 3.14 版被加入.

typing.NoDefault

  A sentinel object used to indicate that a type parameter has no default value. For example:

      >>> T = TypeVar("T")
      >>> T.__default__ is typing.NoDefault
      True
      >>> S = TypeVar("S", default=None)
      >>> S.__default__ is None
      True

  在 3.13 版被加入.

### 常數

typing.TYPE_CHECKING

  A special constant that is assumed to be `True` by 3rd party static type checkers. It's `False` at runtime.

  A module which is expensive to import, and which only contain types used for typing annotations, can be safely imported inside an `if TYPE_CHECKING:` block. This prevents the module from actually being imported at runtime; annotations aren't eagerly evaluated (see PEP 649) so using undefined symbols in annotations is harmless--as long as you don't later examine them. Your static type analysis tool will set `TYPE_CHECKING` to `True` during static type analysis, which means the module will be imported and the types will be checked properly during such analysis.

  用法：

      if TYPE_CHECKING:
          import expensive_mod

      def fun(arg: expensive_mod.SomeType) -> None:
          local_var: expensive_mod.AnotherType = other_fun()

  If you occasionally need to examine type annotations at runtime which may contain undefined symbols, use `annotationlib.get_annotations()` with a `format` parameter of `annotationlib.Format.STRING` or `annotationlib.Format.FORWARDREF` to safely retrieve the annotations without raising `NameError`.

  在 3.5.2 版被加入.

### 棄用的別名

This module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the `typing` module in order to support parameterizing these generic classes using `[]`. However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support `[]` (see PEP 585).

The redundant types are deprecated as of Python 3.9. However, while the aliases may be removed at some point, removal of these aliases is not currently planned. As such, no deprecation warnings are currently issued by the interpreter for these aliases.

If at some point it is decided to remove these deprecated aliases, a deprecation warning will be issued by the interpreter for at least two releases prior to removal. The aliases are guaranteed to remain in the `typing` module without deprecation warnings until at least Python 3.14.

Type checkers are encouraged to flag uses of the deprecated types if the program they are checking targets a minimum Python version of 3.9 or newer.

#### 內建型別的別名

class typing.Dict(dict, MutableMapping[KT, VT])

  棄用 `dict` 的別名。

  Note that to annotate arguments, it is preferred to use an abstract collection type such as `Mapping` rather than to use `dict` or `typing.Dict`.

  在 3.9 版之後被棄用: `builtins.dict` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.List(list, MutableSequence[T])

  棄用 `list` 的別名。

  Note that to annotate arguments, it is preferred to use an abstract collection type such as `Sequence` or `Iterable` rather than to use `list` or `typing.List`.

  在 3.9 版之後被棄用: `builtins.list` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Set(set, MutableSet[T])

  棄用 `builtins.set` 的別名。

  Note that to annotate arguments, it is preferred to use an abstract collection type such as `collections.abc.Set` rather than to use `set` or `typing.Set`.

  在 3.9 版之後被棄用: `builtins.set` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.FrozenSet(frozenset, AbstractSet[T_co])

  棄用 `builtins.frozenset` 的別名。

  在 3.9 版之後被棄用: `builtins.frozenset` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

typing.Tuple

  棄用 `tuple` 的別名。

  `tuple` and `Tuple` are special-cased in the type system; see 註釋元組 (tuple) for more details.

  在 3.9 版之後被棄用: `builtins.tuple` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Type(Generic[CT_co])

  棄用 `type` 的別名。

  See 類別物件的型別 for details on using `type` or `typing.Type` in type annotations.

  在 3.5.2 版被加入.

  在 3.9 版之後被棄用: `builtins.type` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

#### `collections` 中型別的別名

class typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])

  棄用 `collections.defaultdict` 的別名。

  在 3.5.2 版被加入.

  在 3.9 版之後被棄用: `collections.defaultdict` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])

  棄用 `collections.OrderedDict` 的別名。

  在 3.7.2 版被加入.

  在 3.9 版之後被棄用: `collections.OrderedDict` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])

  棄用 `collections.ChainMap` 的別名。

  在 3.6.1 版被加入.

  在 3.9 版之後被棄用: `collections.ChainMap` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Counter(collections.Counter, Dict[T, int])

  棄用 `collections.Counter` 的別名。

  在 3.6.1 版被加入.

  在 3.9 版之後被棄用: `collections.Counter` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Deque(deque, MutableSequence[T])

  棄用 `collections.deque` 的別名。

  在 3.6.1 版被加入.

  在 3.9 版之後被棄用: `collections.deque` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

#### Aliases to other concrete types

class typing.Pattern
class typing.Match

  Deprecated aliases corresponding to the return types from `re.compile()` and `re.match()`.

  These types (and the corresponding functions) are generic over `AnyStr`. `Pattern` can be specialised as `Pattern[str]` or `Pattern[bytes]`; `Match` can be specialised as `Match[str]` or `Match[bytes]`.

  在 3.9 版之後被棄用: Classes `Pattern` and `Match` from `re` now support `[]`. See PEP 585 and 泛型別名型別.

class typing.Text

  棄用 `str` 的別名。

  `Text` is provided to supply a forward compatible path for Python 2 code: in Python 2, `Text` is an alias for `unicode`.

  Use `Text` to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

      def add_unicode_checkmark(text: Text) -> Text:
          return text + u' \u2713'

  在 3.5.2 版被加入.

  在 3.11 版之後被棄用: Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use `str` instead of `Text`.

#### `collections.abc` 中容器 ABC 的別名

class typing.AbstractSet(Collection[T_co])

  棄用 `collections.abc.Set` 的別名。

  在 3.9 版之後被棄用: `collections.abc.Set` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.ByteString(Sequence[int])

  棄用 `collections.abc.ByteString` 的別名。

  使用 `isinstance(obj, collections.abc.Buffer)` 來測試 `obj` 是否在 runtime 實作了緩衝區協定。在型別註解的使用中，請用 `Buffer` 或明確指定你的程式碼所支援型別的聯集（例如 `bytes | bytearray | memoryview`）。

  `ByteString` 最初被設計為一個抽象類別，以作為 `bytes` 和 `bytearray` 的超型別 (supertype)。然而由於 ABC 從未擁有任何方法，知道一個物件是 `ByteString` 的實例從未真正告訴你任何關於該物件的有用資訊。其他常見的緩衝區型別如 `memoryview` 也從未被理解為 `ByteString` 的子型別（無論是在 runtime 還是由靜態型別檢查器）。

  更多細節請見 PEP 688。

  自從版本 3.9 後不推薦使用，將會自版本 3.17 中移除。.

class typing.Collection(Sized, Iterable[T_co], Container[T_co])

  棄用 `collections.abc.Collection` 的別名。

  在 3.6 版被加入.

  在 3.9 版之後被棄用: `collections.abc.Collection` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Container(Generic[T_co])

  棄用 `collections.abc.Container` 的別名。

  在 3.9 版之後被棄用: `collections.abc.Container` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])

  棄用 `collections.abc.ItemsView` 的別名。

  在 3.9 版之後被棄用: `collections.abc.ItemsView` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.KeysView(MappingView, AbstractSet[KT_co])

  棄用 `collections.abc.KeysView` 的別名。

  在 3.9 版之後被棄用: `collections.abc.KeysView` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Mapping(Collection[KT], Generic[KT, VT_co])

  棄用 `collections.abc.Mapping` 的別名。

  在 3.9 版之後被棄用: `collections.abc.Mapping` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.MappingView(Sized)

  棄用 `collections.abc.MappingView` 的別名。

  在 3.9 版之後被棄用: `collections.abc.MappingView` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.MutableMapping(Mapping[KT, VT])

  棄用 `collections.abc.MutableMapping` 的別名。

  在 3.9 版之後被棄用: `collections.abc.MutableMapping` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.MutableSequence(Sequence[T])

  棄用 `collections.abc.MutableSequence` 的別名。

  在 3.9 版之後被棄用: `collections.abc.MutableSequence` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.MutableSet(AbstractSet[T])

  棄用 `collections.abc.MutableSet` 的別名。

  在 3.9 版之後被棄用: `collections.abc.MutableSet` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

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

  棄用 `collections.abc.Sequence` 的別名。

  在 3.9 版之後被棄用: `collections.abc.Sequence` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.ValuesView(MappingView, Collection[_VT_co])

  棄用 `collections.abc.ValuesView` 的別名。

  在 3.9 版之後被棄用: `collections.abc.ValuesView` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

#### `collections.abc` 中非同步 ABC 的別名

class typing.Coroutine(Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType])

  棄用 `collections.abc.Coroutine` 的別名。

  See Annotating generators and coroutines for details on using `collections.abc.Coroutine` and `typing.Coroutine` in type annotations.

  在 3.5.3 版被加入.

  在 3.9 版之後被棄用: `collections.abc.Coroutine` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.AsyncGenerator(AsyncIterator[YieldType], Generic[YieldType, SendType])

  棄用 `collections.abc.AsyncGenerator` 的別名。

  See Annotating generators and coroutines for details on using `collections.abc.AsyncGenerator` and `typing.AsyncGenerator` in type annotations.

  在 3.6.1 版被加入.

  在 3.9 版之後被棄用: `collections.abc.AsyncGenerator` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

  在 3.13 版的變更: `SendType` 參數現在有預設值。

class typing.AsyncIterable(Generic[T_co])

  棄用 `collections.abc.AsyncIterable` 的別名。

  在 3.5.2 版被加入.

  在 3.9 版之後被棄用: `collections.abc.AsyncIterable` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.AsyncIterator(AsyncIterable[T_co])

  棄用 `collections.abc.AsyncIterator` 的別名。

  在 3.5.2 版被加入.

  在 3.9 版之後被棄用: `collections.abc.AsyncIterator` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Awaitable(Generic[T_co])

  棄用 `collections.abc.Awaitable` 的別名。

  在 3.5.2 版被加入.

  在 3.9 版之後被棄用: `collections.abc.Awaitable` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

#### Aliases to other ABCs in `collections.abc`

class typing.Iterable(Generic[T_co])

  棄用 `collections.abc.Iterable` 的別名。

  在 3.9 版之後被棄用: `collections.abc.Iterable` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Iterator(Iterable[T_co])

  棄用 `collections.abc.Iterator` 的別名。

  在 3.9 版之後被棄用: `collections.abc.Iterator` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

typing.Callable

  棄用 `collections.abc.Callable` 的別名。

  See 註釋 callable 物件 for details on how to use `collections.abc.Callable` and `typing.Callable` in type annotations.

  在 3.9 版之後被棄用: `collections.abc.Callable` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

  在 3.10 版的變更: `Callable` 現已支援 `ParamSpec` 以及 `Concatenate`。請參閱 PEP 612 閱讀詳細內容。

class typing.Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])

  棄用 `collections.abc.Generator` 的別名。

  See Annotating generators and coroutines for details on using `collections.abc.Generator` and `typing.Generator` in type annotations.

  在 3.9 版之後被棄用: `collections.abc.Generator` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

  在 3.13 版的變更: Default values for the send and return types were added.

class typing.Hashable

  棄用 `collections.abc.Hashable` 的別名。

  在 3.12 版之後被棄用: 改為直接使用 `collections.abc.Hashable`。

class typing.Reversible(Iterable[T_co])

  棄用 `collections.abc.Reversible` 的別名。

  在 3.9 版之後被棄用: `collections.abc.Reversible` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

class typing.Sized

  棄用 `collections.abc.Sized` 的別名。

  在 3.12 版之後被棄用: 改為直接使用 `collections.abc.Sized`。

#### `contextlib` ABC 的別名

class typing.ContextManager(Generic[T_co, ExitT_co])

  Deprecated alias to `contextlib.AbstractContextManager`.

  The first type parameter, `T_co`, represents the type returned by the `__enter__()` method. The optional second type parameter, `ExitT_co`, which defaults to `bool | None`, represents the type returned by the `__exit__()` method.

  在 3.5.4 版被加入.

  在 3.9 版之後被棄用: `contextlib.AbstractContextManager` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

  在 3.13 版的變更: Added the optional second type parameter, `ExitT_co`.

class typing.AsyncContextManager(Generic[T_co, AExitT_co])

  Deprecated alias to `contextlib.AbstractAsyncContextManager`.

  The first type parameter, `T_co`, represents the type returned by the `__aenter__()` method. The optional second type parameter, `AExitT_co`, which defaults to `bool | None`, represents the type returned by the `__aexit__()` method.

  在 3.6.2 版被加入.

  在 3.9 版之後被棄用: `contextlib.AbstractAsyncContextManager` now supports subscripting (`[]`). See PEP 585 and 泛型別名型別.

  在 3.13 版的變更: Added the optional second type parameter, `AExitT_co`.

## 主要功能的棄用時程表

Certain features in `typing` are deprecated and may be removed in a future version of Python. The following table summarizes major deprecations for your convenience. This is subject to change, and not all deprecations are listed.

Feature | 棄用於 | Projected removal | PEP/issue
--- | --- | --- | ---
`typing` versions of standard collections | 3.9 | Undecided (see 棄用的別名 for more information) | PEP 585
`typing.ByteString` | 3.9 | 3.17 | gh-91896
`typing.Text` | 3.11 | Undecided | gh-92332
`typing.Hashable` 和 `typing.Sized` | 3.12 | Undecided | gh-94309
`typing.TypeAlias` | 3.12 | Undecided | PEP 695
`@typing.no_type_check_decorator` | 3.13 | 3.15 | gh-106309
`typing.AnyStr` | 3.13 | 3.18 | gh-105578