python / python/mypy

Should a method name shadow outer names when quoted or with PEP563?

Ouverte
#18,525 4 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

bug topic-quoted-annotations topic-runtime-semantics
Langage dominant
Python
Étoiles
20.6k
Forks
3.3k
Métriques de merge des PR
Métriques de PR en attente

Description

Bug Report

If a class defines a method with a name shadowing outer name, mypy always rejects it in annotations.

To Reproduce

Consider the following snippet (playground):

#from __future__ import annotations

from typing import get_type_hints, get_origin

class Foo:
    def list(self) -> None: ...
    
    def method(self) -> list[str]:  # E: Function "__main__.Foo.list" is not valid as a type  [valid-type]
        return [""]

Foo().method().append("")  # E: "list?[builtins.str]" has no attribute "append"  [attr-defined]

if get_origin(get_type_hints(Foo.method)['return']) is list:
    print("Resolved to builtins.list")
else:
    print("Resolved as something else")

When run against it, mypy is producing a correct valid-type error, matching runtime behaviour.

$ mypy a.py
a.py:8: error: Function "a.Foo.list" is not valid as a type  [valid-type]
a.py:8: note: Perhaps you need "Callable[...]" or a callback protocol?
a.py:11: error: "list?[builtins.str]" has no attribute "append"  [attr-defined]
Found 2 errors in 1 file (checked 1 source file)

$ pyright a.py
/tmp/tmp.StzhaQlnmA/a.py
  /tmp/tmp.StzhaQlnmA/a.py:8:25 - error: Expected class but received "(self: Self@Foo) -> None" (reportGeneralTypeIssues)
1 error, 0 warnings, 0 informations 

$ python a.py
Traceback (most recent call last):
  File "/tmp/tmp.StzhaQlnmA/a.py", line 5, in <module>
    class Foo:
    ...<3 lines>...
            return [""]
  File "/tmp/tmp.StzhaQlnmA/a.py", line 8, in Foo
    def method(self) -> list[str]:  # E: Function "__main__.Foo.list" is not valid as a type  [valid-type]
                        ~~~~^^^^^
TypeError: 'function' object is not subscriptable

Now let's uncomment the future import or quote list[int] (both behave equivalently).

from __future__ import annotations

from typing import get_type_hints, get_origin

class Foo:
    def list(self) -> None: ...
    
    def method(self) -> list[str]:  # E: Function "__main__.Foo.list" is not valid as a type  [valid-type]
        return [""]

Foo().method().append("")  # E: "list?[builtins.str]" has no attribute "append"  [attr-defined]

if get_origin(get_type_hints(Foo.method)['return']) is list:
    print("Resolved to builtins.list")
else:
    print("Resolved as something else")
$ mypy a.py
a.py:8: error: Function "a.Foo.list" is not valid as a type  [valid-type]
a.py:8: note: Perhaps you need "Callable[...]" or a callback protocol?
a.py:11: error: "list?[builtins.str]" has no attribute "append"  [attr-defined]
Found 2 errors in 1 file (checked 1 source file)

$ pyright a.py
0 errors, 0 warnings, 0 informations 

$ python a.py
Resolved to builtins.list

Runtime resolution also (unsurprisingly, probably) works as intended, so mypy does not model runtime semantics correctly?

Expected Behavior

Snippet with PEP563 enabled should pass mypy check

Actual Behavior

a.py:8: error: Function "a.Foo.list" is not valid as a type  [valid-type]
a.py:8: note: Perhaps you need "Callable[...]" or a callback protocol?
a.py:11: error: "list?[builtins.str]" has no attribute "append"  [attr-defined]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.14.1 and latest master
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.13

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Commencez par exécuter mypy sur le reproducteur fourni avec et sans annotations entre guillemets ou avec PEP 563 activé, en comparant le résultat avec la résolution à l’exécution et pyright. Suivez le chemin de résolution des noms d’annotations pour les noms de méthodes qui masquent des noms externes, puis ajoutez une couverture pour les cas démontrés et vérifiez que les contrôles attendus réussissent.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
python
Domaine
compilers
Type d'issue
Bug
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
42/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.