I've got a class which has a method that creates instances of the class.
class Bar:
@classmethod
def create(cls, foo: int):
return cls(foo)
def __init__(self, foo: int) -> None:
pass
When I run mypy against it, it says mypytest.py:4: error: Too many arguments for "Bar"
It seems like a bug to me, because this works fine
class Bar:
@classmethod
def create(cls, foo):
return cls(foo)
def __init__(self, foo: int) -> None:
pass
I don't understand why a class method which defines the type of a parameter should break the creation of an instance. Am I missing something?
The answer is simple, just place the __init__
method first. For example this works fine:
class Bar:
def __init__(self, foo: int) -> None:
pass
@classmethod
def create(cls, foo: int):
return cls(foo)
For some technical reasons, mypy currently behaves unexpectedly in some corner cases if __init__
(or __new__
) is not the first method in the class definition. I think I have already seen a similar problem, but can't find an issue on mypy tracker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With