The type of cls within bar() in the following code is def () -> Foo unless the __init__ is moved to before the classmethod:
class Foo(object):
@classmethod
def bar(cls):
# type: () -> Foo
reveal_type(cls)
return cls("bar")
def __init__(self, baz):
# type: (str) -> None
self.baz = baz
Probably related:
class Example:
@classmethod
def example(cls, arg1: float, arg2: str) -> Example:
return cls(arg1=arg1, arg2=arg2)
def __init__(self, arg1: float, arg2: str) -> None:
pass
Reports:
example3.py: note: In member "example" of class "Example":
example3.py:7: error: Unexpected keyword argument "arg1" for "Example"
example3.py:7: error: Unexpected keyword argument "arg2" for "Example"
But passes checks if __init__ is moved before the classmethod.
Adding reveal_type with the __init__ method last shows:
example3.py:7: error: Revealed type is 'def () -> example3.Example'
And with __init__ first:
example3.py:11: error: Revealed type is 'def (arg1: builtins.float, arg2: builtins.str) -> example3.Example'
(Raising priority to normal, since this have been reported twice after the original issue.)
+1 on this, thanks @ilevkivskyi
+1, this is also affecting my work
Yeah, my behavior shows that it sometimes works in the wrong order. (see #4290)
Bumping to high-pri because this is happening frequently and the workaround is non-obvious (see #2324).
Hello! We encountered this bug on the very first day of mypy usage. Is there any reason it's not fixed yet? I would like to solve this issue, but it's nice to know up front if it's extremely hard to do something about it.
There probably isn't any particular reason why this hasn't been fixed -- other than there being a lot of other high-priority work as well.
This doesn't sound like it would be very hard to fix (but probably not entirely trivial either). The core team is planning to allocate a block of time focused on fixing high-priority bugs in the next couple of months, and hopefully this gets fixed then.
I've spent some time trying to find a solution, and here is my attempt: https://github.com/python/mypy/pull/5501
I've got a PR about to go up that fixes this as a side effect of changing the type of classmethod first arguments to be a TypeType
@msullivan There is an existing PR. Please take a look at the questions that appeared there (interactions with fine-grained mode, plugins, forward references, generics, and overloads).
@msullivan Forgot to add the PR number, here it is https://github.com/python/mypy/pull/5501
Most helpful comment
Bumping to high-pri because this is happening frequently and the workaround is non-obvious (see #2324).