1.. _libraries:
2
3***********************
4Typing Python Libraries
5***********************
6
7Much of Python’s popularity can be attributed to the rich collection of
8Python libraries available to developers. Authors of these libraries
9play an important role in improving the experience for Python
10developers. This document provides some recommendations and guidance for
11Python library authors.
12
13These recommendations are intended to provide the following benefits:
14
151. Consumers of libraries should have a great coding experience with
16   fast and accurate completion suggestions, class and function
17   documentation, signature help (including parameter default values),
18   hover text, and auto-imports. This should happen by default without
19   needing to download extra packages and without any special
20   configuration. These features should be consistent across the Python
21   ecosystem regardless of a developer’s choice of editor, IDE, notebook
22   environment, etc.
232. Consumers of libraries should be able to rely on complete and
24   accurate type information so static type checkers can detect and
25   report type inconsistencies and other violations of the interface
26   contract.
273. Library authors should be able to specify a well-defined interface
28   contract that is enforced by tools. This allows a library
29   implementation to evolve and improve without breaking consumers of
30   the library.
314. Library authors should have the benefits of static type checking to
32   produce high-quality, bug-free implementations.
33
34Inlined Type Annotations and Type Stubs
35=======================================
36
37`PEP 561 <https://www.python.org/dev/peps/pep-0561/>`__ documents
38several ways type information can be delivered for a library: inlined
39type annotations, type stub files included in the package, a separate
40companion type stub package, and type stubs in the typeshed repository.
41Some of these options fall short on delivering the benefits above. We
42therefore provide the following more specific guidance to library
43authors.
44
45.. note::
46   All libraries should include inlined type annotations for the
47   functions, classes, methods, and constants that comprise the public
48   interface for the library.
49
50Inlined type annotations should be included directly within the source
51code that ships with the package. Of the options listed in PEP 561,
52inlined type annotations offer the most benefits. They typically require
53the least effort to add and maintain, they are always consistent with
54the implementation, and docstrings and default parameter values are
55readily available, allowing language servers to enhance the development
56experience.
57
58There are cases where inlined type annotations are not possible — most
59notably when a library’s exposed functionality is implemented in a
60language other than Python.
61
62.. note::
63   Libraries that expose symbols implemented in languages other than
64   Python should include stub (``.pyi``) files that describe the types for
65   those symbols. These stubs should also contain docstrings and default
66   parameter values.
67
68In many existing type stubs (such as those found in typeshed), default
69parameter values are replaced with with ``...`` and all docstrings are
70removed. We recommend that default values and docstrings remain within
71the type stub file so language servers can display this information to
72developers.
73
74Library Interface
75=================
76
77`PEP 561 <https://www.python.org/dev/peps/pep-0561/>`__ indicates that a
78``py.typed`` marker file must be included in the package if the author
79wishes to support type checking of their code.
80
81If a ``py.typed`` module is present, a type checker will treat all modules
82within that package (i.e. all files that end in ``.py`` or ``.pyi``) as
83importable unless the file name begins with an underscore. These modules
84comprise the supported interface for the library.
85
86Each module exposes a set of symbols. Some of these symbols are
87considered "private” — implementation details that are not part of the
88library’s interface. Type checkers can use the following rules
89to determine which symbols are visible outside of the package.
90
91-  Symbols whose names begin with an underscore (but are not dunder
92   names) are considered private.
93-  Imported symbols are considered private by default. If they use the
94   ``import A as A`` (a redundant module alias), ``from X import A as A`` (a
95   redundant symbol alias), or ``from . import A`` forms, symbol ``A`` is
96   not private unless the name begins with an underscore. If a file
97   ``__init__.py`` uses form ``from .A import X``, symbol ``A`` is treated
98   likewise. If a wildcard import (of the form ``from X import *``) is
99   used, all symbols referenced by the wildcard are not private.
100-  A module can expose an ``__all__`` symbol at the module level that
101   provides a list of names that are considered part of the interface.
102   This overrides all other rules above, allowing imported symbols or
103   symbols whose names begin with an underscore to be included in the
104   interface.
105-  Local variables within a function (including nested functions) are
106   always considered private.
107
108The following idioms are supported for defining the values contained
109within ``__all__``. These restrictions allow type checkers to statically
110determine the value of ``__all__``.
111
112-  ``__all__ = ('a', b')``
113-  ``__all__ = ['a', b']``
114-  ``__all__ += ['a', b']``
115-  ``__all__ += submodule.__all__``
116-  ``__all__.extend(['a', b'])``
117-  ``__all__.extend(submodule.__all__)``
118-  ``__all__.append('a')``
119-  ``__all__.remove('a')``
120
121Type Completeness
122=================
123
124A “py.typed” library should aim to be type complete so that type
125checking and inspection can work to their full extent. Here we say that a
126library is “type complete” if all of the symbols
127that comprise its interface have type annotations that refer to types
128that are fully known. Private symbols are exempt.
129
130The following are best practice recommendations for how to define “type complete”:
131
132Classes:
133
134-  All class variables, instance variables, and methods that are
135   “visible” (not overridden) are annotated and refer to known types
136-  If a class is a subclass of a generic class, type arguments are
137   provided for each generic type parameter, and these type arguments
138   are known types
139
140Functions and Methods:
141
142-  All input parameters have type annotations that refer to known types
143-  The return parameter is annotated and refers to a known type
144-  The result of applying one or more decorators results in a known type
145
146Type Aliases:
147
148-  All of the types referenced by the type alias are known
149
150Variables:
151
152-  All variables have type annotations that refer to known types
153
154Type annotations can be omitted in a few specific cases where the type
155is obvious from the context:
156
157-  Constants that are assigned simple literal values
158   (e.g. ``RED = '#F00'`` or ``MAX_TIMEOUT = 50`` or
159   ``room_temperature: Final = 20``). A constant is a symbol that is
160   assigned only once and is either annotated with ``Final`` or is named
161   in all-caps. A constant that is not assigned a simple literal value
162   requires explicit annotations, preferably with a ``Final`` annotation
163   (e.g. ``WOODWINDS: Final[List[str]] = ['Oboe', 'Bassoon']``).
164-  Enum values within an Enum class do not require annotations because
165   they take on the type of the Enum class.
166-  Type aliases do not require annotations. A type alias is a symbol
167   that is defined at a module level with a single assignment where the
168   assigned value is an instantiable type, as opposed to a class
169   instance
170   (e.g. ``Foo = Callable[[Literal["a", "b"]], Union[int, str]]`` or
171   ``Bar = Optional[MyGenericClass[int]]``).
172-  The “self” parameter in an instance method and the “cls” parameter in
173   a class method do not require an explicit annotation.
174-  The return type for an ``__init__`` method does not need to be
175   specified, since it is always ``None``.
176-  The following module-level symbols do not require type annotations:
177   ``__all__``,\ ``__author__``, ``__copyright__``, ``__email__``,
178   ``__license__``, ``__title__``, ``__uri__``, ``__version__``.
179-  The following class-level symbols do not require type annotations:
180   ``__class__``, ``__dict__``, ``__doc__``, ``__module__``,
181   ``__slots__``.
182
183Examples of known and unknown types
184~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
185
186.. code:: python
187
188
189   # Variable with unknown type
190   a = [3, 4, 5]
191
192   # Variable with known type
193   a: List[int] = [3, 4, 5]
194
195   # Type alias with partially unknown type (because type
196   # arguments are missing for list and dict)
197   DictOrList = Union[list, dict]
198
199   # Type alias with known type
200   DictOrList = Union[List[Any], Dict[str, Any]]
201
202   # Generic type alias with known type
203   _T = TypeVar("_T")
204   DictOrList = Union[List[_T], Dict[str, _T]]
205
206   # Function with known type
207   def func(a: Optional[int], b: Dict[str, float] = {}) -> None:
208       pass
209
210   # Function with partially unknown type (because type annotations
211   # are missing for input parameters and return type)
212   def func(a, b):
213       pass
214
215   # Function with partially unknown type (because of missing
216   # type args on Dict)
217   def func(a: int, b: Dict) -> None:
218       pass
219
220   # Function with partially unknown type (because return type
221   # annotation is missing)
222   def func(a: int, b: Dict[str, float]):
223       pass
224
225   # Decorator with partially unknown type (because type annotations
226   # are missing for input parameters and return type)
227   def my_decorator(func):
228       return func
229
230   # Function with partially unknown type (because type is obscured
231   # by untyped decorator)
232   @my_decorator
233   def func(a: int) -> str:
234       pass
235
236
237   # Class with known type
238   class MyClass:
239       height: float = 2.0
240
241       def __init__(self, name: str, age: int):
242           self.age: int = age
243
244       @property
245       def name(self) -> str:
246           ...
247
248   # Class with partially unknown type
249   class MyClass:
250       # Missing type annotation for class variable
251       height = 2.0
252
253       # Missing input parameter annotations
254       def __init__(self, name, age):
255           # Missing type annotation for instance variable
256           self.age = age
257
258       # Missing return type annotation
259       @property
260       def name(self):
261           ...
262
263   # Class with partially unknown type
264   class BaseClass:
265       # Missing type annotation
266       height = 2.0
267
268       # Missing type annotation
269       def get_stuff(self):
270           ...
271
272   # Class with known type (because it overrides all symbols
273   # exposed by BaseClass that have incomplete types)
274   class DerivedClass(BaseClass):
275       height: float
276
277       def get_stuff(self) -> str:
278           ...
279
280   # Class with partially unknown type because base class
281   # (dict) is generic, and type arguments are not specified.
282   class DictSubclass(dict):
283       pass
284
285Best Practices for Inlined Types
286================================
287
288Wide vs. Narrow Types
289~~~~~~~~~~~~~~~~~~~~~
290
291In type theory, when comparing two types that are related to each other,
292the “wider” type is the one that is more general, and the “narrower”
293type is more specific. For example, ``Sequence[str]`` is a wider type
294than ``List[str]`` because all ``List`` objects are also ``Sequence``
295objects, but the converse is not true. A subclass is narrower than a
296class it derives from. A union of types is wider than the individual
297types that comprise the union.
298
299In general, a function input parameter should be annotated with the
300widest possible type supported by the implementation. For example, if
301the implementation requires the caller to provide an iterable collection
302of strings, the parameter should be annotated as ``Iterable[str]``, not
303as ``List[str]``. The latter type is narrower than necessary, so if a
304user attempts to pass a tuple of strings (which is supported by the
305implementation), a type checker will complain about a type
306incompatibility.
307
308As a specific application of the “use the widest type possible” rule,
309libraries should generally use immutable forms of container types
310instead of mutable forms (unless the function needs to modify the
311container). Use ``Sequence`` rather than ``List``, ``Mapping`` rather
312than ``Dict``, etc. Immutable containers allow for more flexibility
313because their type parameters are covariant rather than invariant. A
314parameter that is typed as ``Sequence[Union[str, int]]`` can accept a
315``List[int]``, ``Sequence[str]``, and a ``Sequence[int]``. But a
316parameter typed as ``List[Union[str, int]]`` is much more restrictive
317and accepts only a ``List[Union[str, int]]``.
318
319Overloads
320~~~~~~~~~
321
322If a function or method can return multiple different types and those
323types can be determined based on the presence or types of certain
324parameters, use the ``@overload`` mechanism defined in `PEP
325484 <https://www.python.org/dev/peps/pep-0484/#id45>`__. When overloads
326are used within a “.py” file, they must appear prior to the function
327implementation, which should not have an ``@overload`` decorator.
328
329Keyword-only Parameters
330~~~~~~~~~~~~~~~~~~~~~~~
331
332If a function or method is intended to take parameters that are
333specified only by name, use the keyword-only separator (``*``).
334
335.. code:: python
336
337   def create_user(age: int, *, dob: Optional[date] = None):
338       ...
339
340Annotating Decorators
341~~~~~~~~~~~~~~~~~~~~~
342
343Decorators modify the behavior of a class or a function. Providing
344annotations for decorators is straightforward if the decorator retains
345the original signature of the decorated function.
346
347.. code:: python
348
349   _F = TypeVar("_F", bound=Callable[..., Any])
350
351   def simple_decorator(_func: _F) -> _F:
352       """
353        Simple decorators are invoked without parentheses like this:
354          @simple_decorator
355          def my_function(): ...
356        """
357      ...
358
359   def complex_decorator(*, mode: str) -> Callable[[_F], _F]:
360       """
361        Complex decorators are invoked with arguments like this:
362          @complex_decorator(mode="easy")
363          def my_function(): ...
364        """
365      ...
366
367Decorators that mutate the signature of the decorated function present
368challenges for type annotations. The ``ParamSpec`` and ``Concatenate``
369mechanisms described in `PEP
370612 <https://www.python.org/dev/peps/pep-0612/>`__ provide some help
371here, but these are available only in Python 3.10 and newer. More
372complex signature mutations may require type annotations that erase the
373original signature, thus blinding type checkers and other tools that
374provide signature assistance. As such, library authors are discouraged
375from creating decorators that mutate function signatures in this manner.
376
377Generic Classes and Functions
378~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379
380Classes and functions that can operate in a generic manner on various
381types should declare themselves as generic using the mechanisms
382described in `PEP 484 <https://www.python.org/dev/peps/pep-0484/>`__.
383This includes the use of ``TypeVar`` symbols. Typically, a ``TypeVar``
384should be private to the file that declares it, and should therefore
385begin with an underscore.
386
387Type Aliases
388~~~~~~~~~~~~
389
390Type aliases are symbols that refer to other types. Generic type aliases
391(those that refer to unspecialized generic classes) are supported by
392most type checkers.
393
394`PEP 613 <https://www.python.org/dev/peps/pep-0613/>`__ provides a way
395to explicitly designate a symbol as a type alias using the new TypeAlias
396annotation.
397
398.. code:: python
399
400   # Simple type alias
401   FamilyPet = Union[Cat, Dog, GoldFish]
402
403   # Generic type alias
404   ListOrTuple = Union[List[_T], Tuple[_T, ...]]
405
406   # Recursive type alias
407   TreeNode = Union[LeafNode, List["TreeNode"]]
408
409   # Explicit type alias using PEP 613 syntax
410   StrOrInt: TypeAlias = Union[str, int]
411
412Abstract Classes and Methods
413~~~~~~~~~~~~~~~~~~~~~~~~~~~~
414
415Classes that must be subclassed should derive from ``ABC``, and methods
416or properties that must be overridden should be decorated with the
417``@abstractmethod`` decorator. This allows type checkers to validate
418that the required methods have been overridden and provide developers
419with useful error messages when they are not. It is customary to
420implement an abstract method by raising a ``NotImplementedError``
421exception.
422
423.. code:: python
424
425   from abc import ABC, abstractmethod
426
427   class Hashable(ABC):
428      @property
429      @abstractmethod
430      def hash_value(self) -> int:
431         """Subclasses must override"""
432         raise NotImplementedError()
433
434      @abstractmethod
435      def print(self) -> str:
436         """Subclasses must override"""
437         raise NotImplementedError()
438
439Final Classes and Methods
440~~~~~~~~~~~~~~~~~~~~~~~~~
441
442Classes that are not intended to be subclassed should be decorated as
443``@final`` as described in `PEP
444591 <https://www.python.org/dev/peps/pep-0591/>`__. The same decorator
445can also be used to specify methods that cannot be overridden by
446subclasses.
447
448Literals
449~~~~~~~~
450
451Type annotations should make use of the Literal type where appropriate,
452as described in `PEP 586 <https://www.python.org/dev/peps/pep-0586/>`__.
453Literals allow for more type specificity than their non-literal
454counterparts.
455
456Constants
457~~~~~~~~~
458
459Constant values (those that are read-only) can be specified using the
460Final annotation as described in `PEP
461591 <https://www.python.org/dev/peps/pep-0591/>`__.
462
463Type checkers will also typically treat variables that are named using
464all upper-case characters as constants.
465
466In both cases, it is OK to omit the declared type of a constant if it is
467assigned a literal str, int, float, bool or None value. In such cases,
468the type inference rules are clear and unambiguous, and adding a literal
469type annotation would be redundant.
470
471.. code:: python
472
473   # All-caps constant with inferred type
474   COLOR_FORMAT_RGB = "rgb"
475
476   # All-caps constant with explicit type
477   COLOR_FORMAT_RGB: Literal["rgb"] = "rgb"
478   LATEST_VERSION: Tuple[int, int] = (4, 5)
479
480   # Final variable with inferred type
481   ColorFormatRgb: Final = "rgb"
482
483   # Final variable with explicit type
484   ColorFormatRgb: Final[Literal["rgb"]] = "rgb"
485   LATEST_VERSION: Final[Tuple[int, int]] = (4, 5)
486
487Typed Dictionaries, Data Classes, and Named Tuples
488~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
489
490If your library runs only on newer versions of Python, you are
491encouraged to use some of the new type-friendly classes.
492
493NamedTuple (described in `PEP
494484 <https://www.python.org/dev/peps/pep-0484/>`__) is preferred over
495namedtuple.
496
497Data classes (described in `PEP
498557 <https://www.python.org/dev/peps/pep-0557/>`__) is preferred over
499untyped dictionaries.
500
501TypedDict (described in `PEP
502589 <https://www.python.org/dev/peps/pep-0589/>`__) is preferred over
503untyped dictionaries.
504
505Compatibility with Older Python Versions
506========================================
507
508Each new version of Python from 3.5 onward has introduced new typing
509constructs. This presents a challenge for library authors who want to
510maintain runtime compatibility with older versions of Python. This
511section documents several techniques that can be used to add types while
512maintaining backward compatibility.
513
514Quoted Annotations
515~~~~~~~~~~~~~~~~~~
516
517Type annotations for variables, parameters, and return types can be
518placed in quotes. The Python interpreter will then ignore them, whereas
519a type checker will interpret them as type annotations.
520
521.. code:: python
522
523   # Older versions of Python do not support subscripting
524   # for the OrderedDict type, so the annotation must be
525   # enclosed in quotes.
526   def get_config(self) -> "OrderedDict[str, str]":
527      return self._config
528
529Type Comment Annotations
530~~~~~~~~~~~~~~~~~~~~~~~~
531
532Python 3.0 introduced syntax for parameter and return type annotations,
533as specified in `PEP 484 <https://www.python.org/dev/peps/pep-0484/>`__.
534Python 3.6 introduced support for variable type annotations, as
535specified in `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`__.
536
537If you need to support older versions of Python, type annotations can
538still be provided as “type comments”. These comments take the form #
539type: .
540
541.. code:: python
542
543   class Foo:
544      # Variable type comments go at the end of the line
545      # where the variable is assigned.
546      timeout = None # type: Optional[int]
547
548      # Function type comments can be specified on the
549      # line after the function signature.
550      def send_message(self, name, length):
551         # type: (str, int) -> None
552         ...
553
554      # Function type comments can also specify the type
555      # of each parameter on its own line.
556      def receive_message(
557         self,
558         name, # type: str
559         length # type: int
560      ):
561         # type: () -> Message
562         ...
563
564typing_extensions
565~~~~~~~~~~~~~~~~~
566
567New type features that require runtime support are typically included in
568the stdlib ``typing`` module. Where possible, these new features are
569back-ported to a runtime library called ``typing_extensions`` that works
570with older Python runtimes.
571
572TYPE_CHECKING
573~~~~~~~~~~~~~
574
575The ``typing`` module exposes a variable called ``TYPE_CHECKING`` which
576has a value of False within the Python runtime but a value of True when
577the type checker is performing its analysis. This allows type checking
578statements to be conditionalized.
579
580Care should be taken when using ``TYPE_CHECKING`` because behavioral
581changes between type checking and runtime could mask problems that the
582type checker would otherwise catch.
583
584Non-Standard Type Behaviors
585===========================
586
587Type annotations provide a way to annotate typical type behaviors, but
588some classes implement specialized, non-standard behaviors that cannot
589be described using standard type annotations. For now, such types need
590to be annotated as Any, which is unfortunate because the benefits of
591static typing are lost.
592
593Docstrings
594==========
595
596Docstrings should be provided for all classes, functions, and methods in
597the interface. They should be formatted according to `PEP
598257 <https://www.python.org/dev/peps/pep-0257/>`__.
599
600There is currently no single agreed-upon standard for function and
601method docstrings, but several common variants have emerged. We
602recommend using one of these variants.
603