Skip to content

Remove most mentions of type comments from docs #12683

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions docs/source/cheat_sheet_py3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ and we use it in most examples.
# This is how you declare the type of a variable type in Python 3.6
age: int = 1

# In Python 3.5 and earlier you can use a type comment instead
# (equivalent to the previous definition)
age = 1 # type: int

# You don't need to initialize a variable to annotate it
a: int # Ok (no value at runtime until assigned)

Expand All @@ -45,7 +41,7 @@ Built-in types

.. code-block:: python


from typing import List, Set, Dict, Tuple, Optional

# For simple built-in types, just use the name of the type
Expand All @@ -65,9 +61,6 @@ Built-in types
x: List[int] = [1]
x: Set[int] = {6, 7}

# Same as above, but with type comment syntax (Python 3.5 and earlier)
x = [1] # type: List[int]

# For mappings, we need the types of both keys and values
x: dict[str, float] = {"field": 2.0} # Python 3.9+
x: Dict[str, float] = {"field": 2.0}
Expand Down
13 changes: 0 additions & 13 deletions docs/source/class_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,6 @@ As in Python generally, a variable defined in the class body can be used
as a class or an instance variable. (As discussed in the next section, you
can override this with a :py:data:`~typing.ClassVar` annotation.)

Type comments work as well, if you need to support Python versions earlier
than 3.6:

.. code-block:: python

class A:
x = None # type: list[int] # Declare attribute 'x' of type list[int]

Note that attribute definitions in the class body that use a type comment
are special: a ``None`` value is valid as the initializer, even though
the declared type is not optional. This should be used sparingly, as this can
result in ``None``-related runtime errors that mypy can't detect.

Similarly, you can give explicit types to instance variables defined
in a method:

Expand Down
4 changes: 2 additions & 2 deletions docs/source/command_line.rst
Original file line number Diff line number Diff line change
Expand Up @@ -548,11 +548,11 @@ of the above sections.
from typing import Optional

a = None # Need type annotation here if using --local-partial-types
b = None # type: Optional[int]
b: Optional[int] = None

class Foo:
bar = None # Need type annotation here if using --local-partial-types
baz = None # type: Optional[int]
baz: Optional[int] = None

def __init__(self) -> None:
self.bar = 1
Expand Down
2 changes: 1 addition & 1 deletion docs/source/dynamic_typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ operations:
o.foo() # Error!
o + 2 # Error!
open(o) # Error!
n = 1 # type: int
n: int = 1
n = o # Error!

You can use different :ref:`type narrowing <type-narrowing>`
Expand Down
6 changes: 3 additions & 3 deletions docs/source/generics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,8 @@ In this way, for example, you can typecheck chaining of setter methods:
self.width = w
return self

circle = Circle().set_scale(0.5).set_radius(2.7) # type: Circle
square = Square().set_scale(0.5).set_width(3.2) # type: Square
circle: Circle = Circle().set_scale(0.5).set_radius(2.7)
square: Square = Square().set_scale(0.5).set_width(3.2)

Without using generic ``self``, the last two lines could not be type-checked properly.

Expand All @@ -310,7 +310,7 @@ For class methods, you can also define generic ``cls``, using :py:class:`Type[T]
T = TypeVar('T', bound='Friend')

class Friend:
other = None # type: Friend
other: "Friend" = None

@classmethod
def make_pair(cls: Type[T]) -> tuple[T, T]:
Expand Down
3 changes: 0 additions & 3 deletions docs/source/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,6 @@ syntax like so:
# If you're using Python 3.6+
my_global_dict: Dict[int, float] = {}

# If you want compatibility with even older versions of Python
my_global_dict = {} # type: Dict[int, float]

.. _stubs-intro:

Library stubs and typeshed
Expand Down
19 changes: 3 additions & 16 deletions docs/source/kinds_of_types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -347,23 +347,13 @@ This also works for attributes defined within methods:
def __init__(self) -> None:
self.count: Optional[int] = None

As a special case, you can use a non-optional type when initializing an
attribute to ``None`` inside a class body *and* using a type comment,
since when using a type comment, an initializer is syntactically required,
and ``None`` is used as a dummy, placeholder initializer:
This is not a problem when using variable annotations, since no initial
value is needed:

.. code-block:: python

class Container:
items = None # type: list[str] # OK (only with type comment)

This is not a problem when using variable annotations, since no initializer
is needed:

.. code-block:: python

class Container:
items: list[str] # No initializer
items: list[str] # No initial value

Mypy generally uses the first assignment to a variable to
infer the type of the variable. However, if you assign both a ``None``
Expand Down Expand Up @@ -421,9 +411,6 @@ the runtime with some limitations (see :ref:`runtime_troubles`).

t2: int | None # equivalent to Optional[int]

# Usable in type comments
t3 = 42 # type: int | str

.. _no_strict_optional:

Disabling strict optional checking
Expand Down
8 changes: 4 additions & 4 deletions docs/source/more_types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ implicitly casting from ``UserId`` where ``int`` is expected. Examples:
name_by_id(42) # Fails type check
name_by_id(UserId(42)) # OK

num = UserId(5) + 1 # type: int
num: int = UserId(5) + 1

:py:func:`NewType <typing.NewType>` accepts exactly two arguments. The first argument must be a string literal
containing the name of the new type and must equal the name of the variable to which the new
Expand Down Expand Up @@ -985,7 +985,7 @@ dictionary value depends on the key:

Movie = TypedDict('Movie', {'name': str, 'year': int})

movie = {'name': 'Blade Runner', 'year': 1982} # type: Movie
movie: Movie = {'name': 'Blade Runner', 'year': 1982}

``Movie`` is a ``TypedDict`` type with two items: ``'name'`` (with type ``str``)
and ``'year'`` (with type ``int``). Note that we used an explicit type
Expand Down Expand Up @@ -1080,7 +1080,7 @@ keys. This will be flagged as an error:
.. code-block:: python

# Error: 'year' missing
toy_story = {'name': 'Toy Story'} # type: Movie
toy_story: Movie = {'name': 'Toy Story'}

Sometimes you want to allow keys to be left out when creating a
``TypedDict`` object. You can provide the ``total=False`` argument to
Expand All @@ -1090,7 +1090,7 @@ Sometimes you want to allow keys to be left out when creating a

GuiOptions = TypedDict(
'GuiOptions', {'language': str, 'color': str}, total=False)
options = {} # type: GuiOptions # Okay
options: GuiOptions = {} # Okay
options['language'] = 'en'

You may need to use :py:meth:`~dict.get` to access items of a partial (non-total)
Expand Down
38 changes: 0 additions & 38 deletions docs/source/type_inference_and_annotations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,6 @@ type:

x: Union[int, str] = 1.1 # Error!

The variable annotation syntax is available starting from Python 3.6.
In earlier Python versions, you can use a special comment after an
assignment statement to declare the type of a variable:

.. code-block:: python

x = 1 # type: Union[int, str]

We'll use both syntax variants in examples. The syntax variants are
mostly interchangeable, but the variable annotation syntax allows
defining the type of a variable without initialization, which is not
possible with the comment syntax:

.. code-block:: python

x: str # Declare type of 'x' without initialization

.. note::

The best way to think about this is that the type annotation sets the
Expand Down Expand Up @@ -182,27 +165,6 @@ Working around the issue is easy by adding a type annotation:
a: list[int] = [] # OK
foo(a)

Declaring multiple variable types at a time
*******************************************

You can declare more than a single variable at a time, but only with
a type comment. In order to nicely work with multiple assignment, you
must give each variable a type separately:

.. code-block:: python

i, found = 0, False # type: int, bool

You can optionally use parentheses around the types, assignment targets
and assigned expression:

.. code-block:: python

i, found = 0, False # type: (int, bool) # OK
(i, found) = 0, False # type: int, bool # OK
i, found = (0, False) # type: int, bool # OK
(i, found) = (0, False) # type: (int, bool) # OK

Starred expressions
*******************

Expand Down