Skip to content

Commit b595128

Browse files
committed
Add common issue docs for PEP584 syntax upgrade
As discussed with @AlexWaygood in #14245 (comment) adding a common issue entry for the problem of hitting overshadowing a built-in keyword when upgrading to PEP584 syntax
1 parent b8c03ab commit b595128

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

docs/source/common_issues.rst

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -821,3 +821,55 @@ This is best understood via an example:
821821
To get this code to type check, you could assign ``y = x`` after ``x`` has been
822822
narrowed, and use ``y`` in the inner function, or add an assert in the inner
823823
function.
824+
825+
826+
Upgrading to :pep:`585` syntax
827+
------------------------------
828+
829+
In pre-:pep:`585` syntax type annotations for builtin types such as ``dict``,
830+
``list``, ``tuple``, ``type`` were taken from the :py:mod:`typing` module as
831+
``typing.Dict``, ``typing.List``, ``typing.Tuple``, ``typing.Type`` etc.
832+
833+
When updating a codebase to use modern syntax, you may hit a case such as the following:
834+
835+
.. code-block:: python
836+
837+
from typing import TypeVar
838+
839+
T = TypeVar("T", bound="Foo")
840+
841+
class Foo:
842+
type: str
843+
844+
@classmethod
845+
def bar(cls: type[T], value: str) -> None:
846+
pass # Mypy complains that "Foo.type" is "not valid as a type"
847+
848+
This occurs due to the fact that the class has an attribute named `type`
849+
that shadows the built-in function :py:func:`type`.
850+
To illustrate the issue: at runtime in the following example,
851+
the annotation for `arg` in the `ham` method
852+
is resolved as being the string `"spam"`
853+
due to the fact that method signatures are executed
854+
in the same scope as class attributes:
855+
856+
.. code-block:: pycon
857+
858+
>>> class Eggs:
859+
... type: str = "spam"
860+
... def ham(self, arg: type) -> None:
861+
... pass
862+
...
863+
>>> import inspect
864+
>>> inspect.signature(Eggs.ham)
865+
<Signature (self, arg: 'spam') -> None>
866+
867+
Mypy follows the same scoping semantics as Python at runtime
868+
when resolving references.
869+
To get this code to type-check, therefore, you have the following options:
870+
871+
- Continue using ``typing.Type[]`` for your annotation.
872+
- Add ``import builtins`` to the top of your module and use ``builtins.type[]`` for your annotation.
873+
- Add ``from builtins import type as Type`` to the top of your module and use ``Type[]`` for your annotation
874+
875+
The same thing applies for any other built-in name.

0 commit comments

Comments
 (0)