python / python/mypy

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

Open
#17,021 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.]

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied reproducer, comparing function_pre() and function_post() around SomeClass and its decorated init. Trace how construction is analyzed before the class declaration; done means both assert_type checks recognize SomeClass rather than Any, with the reproducer preserved as a regression case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.