diff --git a/README.md b/README.md index 8bc02d48..43eb7df2 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,8 @@ For conversations that are more suitable to a chat platform, you can use one of ## Repository Content -This GitHub repository is used for several things: +This GitHub repository serves multiple purposes related to Python's static type system: + - The documentation at [typing.python.org](https://typing.python.org/) is maintained in the [docs directory](./docs). This includes the diff --git a/docs/index.rst b/docs/index.rst index 19117d05..60d8e3b3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -69,7 +69,7 @@ Discussions and Support ======================= * `User help forum `_ -* `User chat on Gitter `_ +* `User chat on Gitter `_ * `Developer forum `_ * `Developer mailing list (archived) `_ diff --git a/docs/spec/index.rst b/docs/spec/index.rst index 30210227..a4ca4b98 100644 --- a/docs/spec/index.rst +++ b/docs/spec/index.rst @@ -1,6 +1,11 @@ Specification for the Python type system + ======================================== +This section provides the official specification for Python’s static type system. +It defines the rules, terminology, and behaviors that type checkers and typing-related tools are expected to follow. + + .. toctree:: :maxdepth: 2 :caption: Contents: diff --git a/docs/spec/literal.rst b/docs/spec/literal.rst index 7b0015ca..7b01f9ae 100644 --- a/docs/spec/literal.rst +++ b/docs/spec/literal.rst @@ -8,7 +8,7 @@ Literals ``Literal`` ----------- -(Originally specified in :pep:`586`.) +(Originally specified in :pep:`586`, which introduced ``Literal`` types.) Core Semantics @@ -24,6 +24,24 @@ concrete value. For example, if we define some variable ``foo`` to have type ``Literal[3]``, we are declaring that ``foo`` must be exactly equal to ``3`` and no other value. +Example +^^^^^^^ + +Literal types are most useful when a function accepts only a fixed set of +allowed constant values. Type checkers can then verify that callers provide +only those values. + +.. code-block:: python + + from typing import Literal + + def set_mode(mode: Literal["fast", "slow"]) -> None: + print(f"Running in {mode} mode") + + set_mode("fast") # OK + set_mode("other") # Type checker error + + Given some value ``v`` that is a member of type ``T``, the type ``Literal[v]`` is a subtype of ``T``. For example, ``Literal[3]`` is a subtype of ``int``. @@ -32,6 +50,9 @@ literal type. So, if we have some variable ``foo`` of type ``Literal[3]`` it’s safe to do things like ``foo + 5`` since ``foo`` inherits ``int``’s ``__add__`` method. The resulting type of ``foo + 5`` is ``int``. +The specification does not mandate the level of precision required for such inference, and type checkers may choose to infer a more precise ``Literal`` result where possible. + + This "inheriting" behavior is identical to how we :ref:`handle NewTypes `.