Debian Codegraph @

docs/source/stubs.rst

raw
1 .. _stub-files:
2
3 Stub files
4 ==========
5
6 A *stub file* is a file containing a skeleton of the public interface
7 of that Python module, including classes, variables, functions -- and
8 most importantly, their types.
9
10 Mypy uses stub files stored in the
11 `typeshed <https://github.com/python/typeshed>`_ repository to determine
12 the types of standard library and third-party library functions, classes,
13 and other definitions. You can also create your own stubs that will be
14 used to type check your code.
15
16 Creating a stub
17 ***************
18
19 Here is an overview of how to create a stub file:
20
21 * Write a stub file for the library (or an arbitrary module) and store it as
22 a ``.pyi`` file in the same directory as the library module.
23 * Alternatively, put your stubs (``.pyi`` files) in a directory
24 reserved for stubs (e.g., :file:`myproject/stubs`). In this case you
25 have to set the environment variable ``MYPYPATH`` to refer to the
26 directory. For example::
27
28 $ export MYPYPATH=~/work/myproject/stubs
29
30 Use the normal Python file name conventions for modules, e.g. :file:`csv.pyi`
31 for module ``csv``. Use a subdirectory with :file:`__init__.pyi` for packages. Note
32 that :pep:`561` stub-only packages must be installed, and may not be pointed
33 at through the ``MYPYPATH`` (see :ref:`PEP 561 support <installed-packages>`).
34
35 If a directory contains both a ``.py`` and a ``.pyi`` file for the
36 same module, the ``.pyi`` file takes precedence. This way you can
37 easily add annotations for a module even if you don't want to modify
38 the source code. This can be useful, for example, if you use 3rd party
39 open source libraries in your program (and there are no stubs in
40 typeshed yet).
41
42 That's it!
43
44 Now you can access the module in mypy programs and type check
45 code that uses the library. If you write a stub for a library module,
46 consider making it available for other programmers that use mypy
47 by contributing it back to the typeshed repo.
48
49 Mypy also ships with two tools for making it easier to create and maintain
50 stubs: :ref:`stubgen` and :ref:`stubtest`.
51
52 The following sections explain the kinds of type annotations you can use
53 in your programs and stub files.
54
55 .. note::
56
57 You may be tempted to point ``MYPYPATH`` to the standard library or
58 to the :file:`site-packages` directory where your 3rd party packages
59 are installed. This is almost always a bad idea -- you will likely
60 get tons of error messages about code you didn't write and that
61 mypy can't analyze all that well yet, and in the worst case
62 scenario mypy may crash due to some construct in a 3rd party
63 package that it didn't expect.
64
65 Stub file syntax
66 ****************
67
68 Stub files are written in normal Python syntax, but generally
69 leaving out runtime logic like variable initializers, function bodies,
70 and default arguments.
71
72 If it is not possible to completely leave out some piece of runtime
73 logic, the recommended convention is to replace or elide them with ellipsis
74 expressions (``...``). Each ellipsis below is literally written in the
75 stub file as three dots:
76
77 .. code-block:: python
78
79 # Variables with annotations do not need to be assigned a value.
80 # So by convention, we omit them in the stub file.
81 x: int
82
83 # Function bodies cannot be completely removed. By convention,
84 # we replace them with `...` instead of the `pass` statement.
85 def func_1(code: str) -> int: ...
86
87 # We can do the same with default arguments.
88 def func_2(a: int, b: int = ...) -> int: ...
89
90 .. note::
91
92 The ellipsis ``...`` is also used with a different meaning in
93 :ref:`callable types <callable-types>` and :ref:`tuple types
94 <tuple-types>`.
95
96 Using stub file syntax at runtime
97 *********************************
98
99 You may also occasionally need to elide actual logic in regular
100 Python code -- for example, when writing methods in
101 :ref:`overload variants <function-overloading>` or
102 :ref:`custom protocols <protocol-types>`.
103
104 The recommended style is to use ellipses to do so, just like in
105 stub files. It is also considered stylistically acceptable to
106 throw a :py:exc:`NotImplementedError` in cases where the user of the
107 code may accidentally call functions with no actual logic.
108
109 You can also elide default arguments as long as the function body
110 also contains no runtime logic: the function body only contains
111 a single ellipsis, the pass statement, or a ``raise NotImplementedError()``.
112 It is also acceptable for the function body to contain a docstring.
113 For example:
114
115 .. code-block:: python
116
117 from typing import Protocol
118
119 class Resource(Protocol):
120 def ok_1(self, foo: list[str] = ...) -> None: ...
121
122 def ok_2(self, foo: list[str] = ...) -> None:
123 raise NotImplementedError()
124
125 def ok_3(self, foo: list[str] = ...) -> None:
126 """Some docstring"""
127 pass
128
129 # Error: Incompatible default for parameter "foo" (default has
130 # type "ellipsis", parameter has type "list[str]")
131 def not_ok(self, foo: list[str] = ...) -> None:
132 print(foo)