python / python/mypy

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

Aperta
#18,525 4 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-quoted-annotations topic-runtime-semantics
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo mypy sul riproduttore fornito con e senza annotazioni tra virgolette o con PEP 563 abilitato, confrontando il risultato con la risoluzione a runtime e pyright. Traccia il percorso di risoluzione dei nomi delle annotazioni per i nomi dei metodi che fanno shadowing di nomi esterni, quindi aggiungi la copertura per i casi mostrati e verifica che i controlli previsti vadano a buon fine.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
42/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.