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

function that returns decorator as class member raises "self-argument missing" #15549

Closed
sanjacob opened this issue Jun 29, 2023 · 4 comments
Closed
Labels
bug mypy got something wrong

Comments

@sanjacob
Copy link

Bug Report

Similar to #7778, where having a function that returns a decorator inside a class without a self parameter
is not possible.

To Reproduce
I have this setup to be able to do this inside a class:

@log('hello world')
def method(self):
    ...
from functools import wraps
from typing import Callable

class MyClass:
    def log(text: str):
        def log_decorator(func: Callable) -> Callable:
            @wraps(func)
            def log_wrapper(self):
                func(self)
                print(text) # Passed as param in log
            return log_wrapper
        return log_decorator


    @log('print this')
    def test(self) -> None:
        print('word')

foo = MyClass()
foo.test()

Expected Behavior
mypy should not find any errors with this.

Actual Behavior

mypy test_concept.py
test_concept.py:5: error: Self argument missing for a non-static method (or an invalid type for self)  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.4.1 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10.0
@sanjacob sanjacob added the bug mypy got something wrong label Jun 29, 2023
@rafales
Copy link

rafales commented Aug 20, 2023

This is not entirely valid code. MyClass now has an invalid MyClass.log method:

m = MyClass()
m.log()  # doesn't make any sense

@JelleZijlstra
Copy link
Member

I'm going to say this is out of scope. This use case is very rare, and any reasonable solution is going to make it a lot harder for mypy to correctly report cases where the user forgot to add self (a common mistake).

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Aug 21, 2023
@erictraut
Copy link

If you mark the method log as a @staticmethod, it will work fine at runtime and type check without errors.

@geipel
Copy link

geipel commented Jul 2, 2024

If you mark the method log as a @staticmethod, it will work fine at runtime and type check without errors.

That does run for more recent python, but not 3.8.10 (for example).

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

5 participants