]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-130117: Document why nested `Union`, `Literal`, and `Annotated` types referenced...
authorValentin Berlier <berlier.v@gmail.com>
Tue, 6 May 2025 02:05:16 +0000 (04:05 +0200)
committerGitHub <noreply@github.com>
Tue, 6 May 2025 02:05:16 +0000 (19:05 -0700)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Doc/library/typing.rst

index 3afcba6e898a634dc84ed9124d9cb2956cd209a2..54cc3ea3311adf339780c08c794865de4e56f929 100644 (file)
@@ -1098,6 +1098,12 @@ These can be used as types in annotations. They all support subscription using
 
        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 :class:`TypeAliasType`::
+
+       type A = Union[int, str]
+       Union[A, float] != Union[int, str, float]
+
    * Unions of a single argument vanish, e.g.::
 
        Union[int] == int  # The constructor actually returns int
@@ -1230,6 +1236,32 @@ These can be used as types in annotations. They all support subscription using
    is allowed as type argument to ``Literal[...]``, but type checkers may
    impose restrictions. See :pep:`586` for more details about literal types.
 
+   Additional details:
+
+   * The arguments must be literal values and there must be at least one.
+
+   * Nested ``Literal`` types are flattened, e.g.::
+
+      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 :class:`TypeAliasType`::
+
+      type A = Literal[1, 2]
+      assert Literal[A, 3] != Literal[1, 2, 3]
+
+   * Redundant arguments are skipped, e.g.::
+
+      assert Literal[1, 2, 1] == Literal[1, 2]
+
+   * When comparing literals, the argument order is ignored, e.g.::
+
+      assert Literal[1, 2] == Literal[2, 1]
+
+   * You cannot subclass or instantiate a ``Literal``.
+
+   * You cannot write ``Literal[X][Y]``.
+
    .. versionadded:: 3.8
 
    .. versionchanged:: 3.9.1
@@ -1400,6 +1432,14 @@ These can be used as types in annotations. They all support subscription using
           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 :class:`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[