python / python/mypy

using __new__ with type(x: T) resolvestype(x: T) as being of type type

Aperta
#10,100 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

The following code passes a MyPy check with flying colors:

from typing import TypeVar, Any
T = TypeVar("T", bound=Any)

def this_one_works(x: T) -> T:
    res = x.__new__(type(x))
    return res

But the following does not:

from typing import TypeVar, Any
T = TypeVar("T", bound=Any)

def this_one_not_so_much(x: T) -> T:
    res = type(x).__new__(type(x))
    return res

Instead it seems to resolve type(x) as <class 'type'> when used with __new__() and complains about missing arguments:

test.py:5: error: No overload variant of "new" of "type" matches argument type "Type[T]"
test.py:5: note: Possible overload variants:
test.py:5: note: def new(cls, cls: Type[type], o: object) -> type
test.py:5: note: def new(cls, cls: Type[type], name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type
Found 1 error in 1 file (checked 1 source file)

Is this expected behavior, or is it resolving incorrectly in the second case?

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 con mypy i due frammenti di codice dell’issue e confrontando come vengono inferiti type(x) e x.new. Segui il percorso del controllo dei tipi per type(x).new e determina se la risoluzione segnalata è prevista; il lavoro è completato quando è stato stabilito il comportamento previsto e il risultato è stato documentato o testato.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
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.