python / python/mypy

Decorators over `__init__()` make classes unconstructable until after the class is declared, even within functions

Aperta
#17,021 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

It should be possible, within a function, to construct an instance of a class which is declared globally later in the module. Applying a decorator factory to a class's __init__() causes constructed instances to have type Any, but only before the class declaration[^1]. (A plain decorator doesn't trigger this issue.)

This probably explains #14519, and may be related to #11293.

To Reproduce

[mypy-play.net]

from __future__ import annotations
from typing import (
        Any,
        Callable,
        TypeVar,
        )
from typing_extensions import (
        assert_type,
        )


Tc = TypeVar('Tc', bound=Callable[..., Any])

def any_decorator_factory() -> Callable[[Tc], Tc]:
    '''this one does nothing
    '''
    def inner(func: Tc) -> Tc:
        return func
    return inner



def function_pre() -> None:
    '''this function is identical to 'function_post()',
       but only this copy generates a mypy error
    '''
    instance = SomeClass()
    assert_type(instance, SomeClass)  # error: type is "Any", not "SomeClass"



class SomeClass:

    @any_decorator_factory()
    def __init__(self):
        pass


def function_post() -> None:
    '''this function is identical to 'function_pre()',
       but only that copy generates a mypy error
    '''
    instance = SomeClass()
    assert_type(instance, SomeClass)  # no error

Expected Behavior

The tool should issue no error for function_pre(); it's just as valid as function_post().

Actual Behavior

Any construction of SomeClass before that type is declared (i.e., before the end of its body) has type Any instead of SomeClass.

Your Environment

  • Mypy version used: master 2024-03-12, 1.9.0
  • Mypy command-line flags: none necessary
  • Mypy configuration options from mypy.ini (and other config files): none necessary
  • Python version used: 3.8, 3.11, 3.12

[^1]: some functions within the class body are affected as well; I haven't narrowed down the exact point constructing the class starts to behave normally, but I can do upon request.

[Edited for clarity, and to simplify the reproduction case by removing vestigial code.]

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 con il reproducer fornito, confrontando function_pre() e function_post() intorno a SomeClass e al suo init decorato. Traccia come viene analizzata la costruzione prima della dichiarazione della classe; il lavoro è completo quando entrambi i controlli assert_type riconoscono SomeClass invece di Any, mantenendo il reproducer come caso di regressione.

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
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.