4
4
Type Stubs
5
5
**********
6
6
7
- Abstract
8
- ========
9
-
10
- Optional type hints were introduced to the Python language in PEP 484
11
- [#pep484 ]_, based on the function annotation syntax from PEP 3107
12
- [#pep3107 ]_. Static type checkers can use type hints to prevent bugs,
13
- documentation tools can automatically add type information,
14
- and IDEs can offer improved autocompletion and support safer refactorings.
7
+ Introduction
8
+ ============
15
9
16
- PEP 484 also introduced *type stubs *, also called *stub files *,
17
- that provide type information for untyped Python packages and modules. Type
18
- stubs serve multiple purposes:
10
+ *type stubs *, also called *stub files *, provide type information for untyped
11
+ Python packages and modules. Type stubs serve multiple purposes:
19
12
20
13
* They are the only way to add type information to extension modules.
21
14
* They can provide type information for packages that do not wish to
@@ -28,27 +21,24 @@ stubs serve multiple purposes:
28
21
API of a package, without including the implementation or private
29
22
members.
30
23
31
- This PEP aims to give guidance to both authors of type stubs and developers
24
+ This document aims to give guidance to both authors of type stubs and developers
32
25
of type checkers and other tools. It describes the constructs that can be used safely in type stubs,
33
26
suggests a style guide for them, and lists constructs that type
34
27
checkers are expected to support.
35
28
36
- Type stubs that only use constructs described in this PEP should work with
37
- all type checkers that also follow this PEP .
29
+ Type stubs that only use constructs described in this document should work with
30
+ all type checkers that also follow this document .
38
31
Type stub authors can elect to use additional constructs, but
39
32
must be prepared that some type checkers will not parse them as expected.
40
33
41
- A type checker that conforms to this PEP will parse a type stub that only uses
34
+ A type checker that conforms to this document will parse a type stub that only uses
42
35
constructs described here without error and will not interpret any
43
36
construct in a contradictory manner. However, type checkers are not
44
37
required to implement checks for all these constructs, and
45
38
can elect to ignore unsupported ones. Additionally type checkers
46
- can support constructs not described in this PEP and tool authors are
39
+ can support constructs not described in this document and tool authors are
47
40
encouraged to experiment with additional features.
48
41
49
- This PEP is intended as a living document and will be updated as new
50
- features are supported or best practices evolve.
51
-
52
42
Syntax
53
43
======
54
44
@@ -84,8 +74,10 @@ Type stubs can be distributed with or separately from the implementation;
84
74
see PEP 561 [#pep561 ]_ for more information. The
85
75
`typeshed <https://github.com/python/typeshed >`_ project
86
76
includes stubs for Python's standard library and several third-party
87
- packages. These are usually distributed with type checkers and do not
88
- require separate installation.
77
+ packages. The stubs for the standard library are usually distributed with type checkers and do not
78
+ require separate installation. Stubs for third-party libraries are
79
+ available on the `Python Package Index <https://pypi.org >`_. A stub package for
80
+ a library called ``widget `` will be called ``types-widget ``.
89
81
90
82
Supported Constructs
91
83
====================
@@ -121,7 +113,9 @@ Two kinds of structured comments are accepted:
121
113
declaring that the variable has type ``X ``. However, PEP 526-style [#pep526 ]_
122
114
variable annotations are preferred over type comments.
123
115
* A ``# type: ignore `` comment at the end of any line, which suppresses all type
124
- errors in that line.
116
+ errors in that line. The type checker mypy supports suppressing certain
117
+ type errors by using ``# type: ignore[error-type] ``. This is not supported
118
+ by other type checkers and should not be used in stubs.
125
119
126
120
Imports
127
121
-------
@@ -168,13 +162,13 @@ By default, ``from foo import *`` imports all names in ``foo`` that
168
162
do not begin with an underscore. When ``__all__ `` is defined, only those names
169
163
specified in ``__all__ `` are imported::
170
164
171
- __all__ = ['public_attr', '_private_looking_public_attr']
165
+ __all__ = ['public_attr', '_private_looking_public_attr']
172
166
173
167
public_attr: int
174
168
_private_looking_public_attr: int
175
169
private_attr: int
176
170
177
- Type checkers can handle cyclic imports in stub files.
171
+ Type checkers support cyclic imports in stub files.
178
172
179
173
Module Level Attributes
180
174
-----------------------
@@ -269,7 +263,7 @@ Alternatively, ``...`` can be used in place of any default value::
269
263
def invalid(a: int = "", b: Foo = Foo()): ...
270
264
271
265
For a class ``C ``, the type of the first argument to a classmethod is
272
- assumed to be ``Type [C] ``, if unannotated. For other non-static methods,
266
+ assumed to be ``type [C] ``, if unannotated. For other non-static methods,
273
267
its type is assumed to be ``C ``::
274
268
275
269
class Foo:
@@ -284,9 +278,9 @@ But::
284
278
_T = TypeVar("_T")
285
279
286
280
class Foo:
287
- def do_things(self: _T): ... # self has type _T
281
+ def do_things(self: _T) -> _T : ... # self has type _T
288
282
@classmethod
289
- def create_it(cls: _T): ... # cls has type _T
283
+ def create_it(cls: _T) -> _T : ... # cls has type _T
290
284
291
285
Using a function or method body other than the ellipsis literal is currently
292
286
unspecified. Stub authors may experiment with other bodies, but it is up to
@@ -310,7 +304,7 @@ type stubs::
310
304
def foo(x: str) -> str: ...
311
305
@overload
312
306
def foo(x: float) -> int: ...
313
- def foo(x: Union[ str, float] ) -> Any: ...
307
+ def foo(x: str | float) -> Any: ...
314
308
315
309
Aliases and NewType
316
310
-------------------
@@ -512,8 +506,8 @@ Such undocumented objects are allowed because omitting objects can confuse
512
506
users. Users who see an error like "module X has no attribute Y" will
513
507
not know whether the error appeared because their code had a bug or
514
508
because the stub is wrong. Although it may also be helpful for a type
515
- checker to point out usage of private objects, we usually prefer false
516
- negatives (no errors for wrong code) over false positives (type errors
509
+ checker to point out usage of private objects, false negatives (no errors for
510
+ wrong code) are preferable over false positives (type errors
517
511
for correct code). In addition, even for private objects a type checker
518
512
can be helpful in pointing out that an incorrect type was used.
519
513
@@ -580,6 +574,9 @@ annotated function ``bar()``::
580
574
581
575
def bar(x: str, y, *, z=...): ...
582
576
577
+ The ``# incomplete `` comment is mainly intended as a reminder for stub
578
+ authors, but can be used by tools to flag such items.
579
+
583
580
Attribute Access
584
581
----------------
585
582
@@ -899,10 +896,10 @@ Types
899
896
Generally, use ``Any `` when a type cannot be expressed appropriately
900
897
with the current type system or using the correct type is unergonomic.
901
898
902
- Use ``float `` instead of ``Union[ int, float] ``.
899
+ Use ``float `` instead of ``int | float ``.
903
900
Use ``None `` instead of ``Literal[None] ``.
904
901
For argument types,
905
- use ``bytes `` instead of ``Union[ bytes, memoryview, bytearray] ``.
902
+ use ``bytes `` instead of ``bytes | memoryview | bytearray ``.
906
903
907
904
Use ``Text `` in stubs that support Python 2 when something accepts both
908
905
``str `` and ``unicode ``. Avoid using ``Text `` in stubs or branches for
@@ -949,8 +946,8 @@ Maybe::
949
946
def foo(self) -> list[int]: ...
950
947
def bar(self) -> Mapping[str]: ...
951
948
952
- Avoid `` Union `` return types, since they require ``isinstance() `` checks.
953
- Use ``Any `` if necessary.
949
+ Avoid union return types, since they require ``isinstance() `` checks.
950
+ Use ``Any `` or `` X | Any `` if necessary.
954
951
955
952
Use built-in generics instead of the aliases from ``typing ``.
956
953
0 commit comments