Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decorating __init__() with a class decorator is not supported #18513

Open
s417-lama opened this issue Jan 23, 2025 · 0 comments
Open

Decorating __init__() with a class decorator is not supported #18513

s417-lama opened this issue Jan 23, 2025 · 0 comments
Labels
bug mypy got something wrong

Comments

@s417-lama
Copy link

Bug Report

I want to define a decorator as a class to decorate another class's methods. However, when __init__() constructor is decorated with that class, mypy reports Unsupported decorated constructor type error.

(For reference) Stackoverflow question I posted: https://stackoverflow.com/questions/79374167/mypy-unsupported-decorated-constructor-type-error-when-decorating-init-w

To Reproduce

from types import MethodType
from typing import TypeVar, Callable, Type, ParamSpec, Generic

T = TypeVar("T")
P = ParamSpec("P")
R = TypeVar("R")

class method_decorator(Generic[P, R]):
    def __init__(self, method: Callable[P, R]):
        self.method = method

    def __get__(self, instance: T | None, cls: Type[T]) -> Callable[..., R]:
        return self if instance is None else MethodType(self, instance)

    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
        return self.method(*args, **kwargs)

class Foo:
    @method_decorator # error: Unsupported decorated constructor type  [misc]
    def __init__(self, x: int):
        self.x = x

    @method_decorator
    def mul(self, a: int) -> int:
        return self.x * a

def gen_foo(x: int) -> Foo:
    return Foo(x) # error: Returning Any from function declared to return "Foo"  [no-any-return]

foo = gen_foo(2)
print(foo.mul(3))

Actual Behavior

$ uv run mypy --strict test.py
test.py:19: error: Unsupported decorated constructor type  [misc]
test.py:28: error: Returning Any from function declared to return "Foo"  [no-any-return]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): default
  • Python version used: 3.11.9
@s417-lama s417-lama added the bug mypy got something wrong label Jan 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant