Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit ce2ea20

Browse filesBrowse files
authored
Various improvements to the Type Stubs document (#846)
* Rename "Abstract" to "Introduction" and remove fluff originally intended for the PEP. * "This PEP" -> "This document" * Remove note about the living document status. This is a given, not that it isn't a PEP anymore. * Third-party stubs are now distributed via PyPI. * Mention "# type: ignore[xxx]". * Fix indentation. * Reformulate sentence about cyclic imports. * Use type vars correctly in example. * Use new union syntax. * Remove "we" from sentence and slightly reformulate. * Clarify that "# incomplete" is mainly intended for stub authors. * Mention "X | Any" return type. Still needs to be explained.
1 parent f5bc93a commit ce2ea20
Copy full SHA for ce2ea20

File tree

Expand file treeCollapse file tree

1 file changed

+31
-34
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+31
-34
lines changed

‎docs/stubs.rst

Copy file name to clipboardExpand all lines: docs/stubs.rst
+31-34Lines changed: 31 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,11 @@
44
Type Stubs
55
**********
66

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+
============
159

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:
1912

2013
* They are the only way to add type information to extension modules.
2114
* They can provide type information for packages that do not wish to
@@ -28,27 +21,24 @@ stubs serve multiple purposes:
2821
API of a package, without including the implementation or private
2922
members.
3023

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
3225
of type checkers and other tools. It describes the constructs that can be used safely in type stubs,
3326
suggests a style guide for them, and lists constructs that type
3427
checkers are expected to support.
3528

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.
3831
Type stub authors can elect to use additional constructs, but
3932
must be prepared that some type checkers will not parse them as expected.
4033

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
4235
constructs described here without error and will not interpret any
4336
construct in a contradictory manner. However, type checkers are not
4437
required to implement checks for all these constructs, and
4538
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
4740
encouraged to experiment with additional features.
4841

49-
This PEP is intended as a living document and will be updated as new
50-
features are supported or best practices evolve.
51-
5242
Syntax
5343
======
5444

@@ -84,8 +74,10 @@ Type stubs can be distributed with or separately from the implementation;
8474
see PEP 561 [#pep561]_ for more information. The
8575
`typeshed <https://github.com/python/typeshed>`_ project
8676
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``.
8981

9082
Supported Constructs
9183
====================
@@ -121,7 +113,9 @@ Two kinds of structured comments are accepted:
121113
declaring that the variable has type ``X``. However, PEP 526-style [#pep526]_
122114
variable annotations are preferred over type comments.
123115
* 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.
125119

126120
Imports
127121
-------
@@ -168,13 +162,13 @@ By default, ``from foo import *`` imports all names in ``foo`` that
168162
do not begin with an underscore. When ``__all__`` is defined, only those names
169163
specified in ``__all__`` are imported::
170164

171-
__all__ = ['public_attr', '_private_looking_public_attr']
165+
__all__ = ['public_attr', '_private_looking_public_attr']
172166

173167
public_attr: int
174168
_private_looking_public_attr: int
175169
private_attr: int
176170

177-
Type checkers can handle cyclic imports in stub files.
171+
Type checkers support cyclic imports in stub files.
178172

179173
Module Level Attributes
180174
-----------------------
@@ -269,7 +263,7 @@ Alternatively, ``...`` can be used in place of any default value::
269263
def invalid(a: int = "", b: Foo = Foo()): ...
270264

271265
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,
273267
its type is assumed to be ``C``::
274268

275269
class Foo:
@@ -284,9 +278,9 @@ But::
284278
_T = TypeVar("_T")
285279

286280
class Foo:
287-
def do_things(self: _T): ... # self has type _T
281+
def do_things(self: _T) -> _T: ... # self has type _T
288282
@classmethod
289-
def create_it(cls: _T): ... # cls has type _T
283+
def create_it(cls: _T) -> _T: ... # cls has type _T
290284

291285
Using a function or method body other than the ellipsis literal is currently
292286
unspecified. Stub authors may experiment with other bodies, but it is up to
@@ -310,7 +304,7 @@ type stubs::
310304
def foo(x: str) -> str: ...
311305
@overload
312306
def foo(x: float) -> int: ...
313-
def foo(x: Union[str, float]) -> Any: ...
307+
def foo(x: str | float) -> Any: ...
314308

315309
Aliases and NewType
316310
-------------------
@@ -512,8 +506,8 @@ Such undocumented objects are allowed because omitting objects can confuse
512506
users. Users who see an error like "module X has no attribute Y" will
513507
not know whether the error appeared because their code had a bug or
514508
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
517511
for correct code). In addition, even for private objects a type checker
518512
can be helpful in pointing out that an incorrect type was used.
519513

@@ -580,6 +574,9 @@ annotated function ``bar()``::
580574

581575
def bar(x: str, y, *, z=...): ...
582576

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+
583580
Attribute Access
584581
----------------
585582

@@ -899,10 +896,10 @@ Types
899896
Generally, use ``Any`` when a type cannot be expressed appropriately
900897
with the current type system or using the correct type is unergonomic.
901898

902-
Use ``float`` instead of ``Union[int, float]``.
899+
Use ``float`` instead of ``int | float``.
903900
Use ``None`` instead of ``Literal[None]``.
904901
For argument types,
905-
use ``bytes`` instead of ``Union[bytes, memoryview, bytearray]``.
902+
use ``bytes`` instead of ``bytes | memoryview | bytearray``.
906903

907904
Use ``Text`` in stubs that support Python 2 when something accepts both
908905
``str`` and ``unicode``. Avoid using ``Text`` in stubs or branches for
@@ -949,8 +946,8 @@ Maybe::
949946
def foo(self) -> list[int]: ...
950947
def bar(self) -> Mapping[str]: ...
951948

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.
954951

955952
Use built-in generics instead of the aliases from ``typing``.
956953

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.