Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does mypy say I have too many arguments

Tags:

python

mypy

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?

like image 753
McKay Avatar asked Nov 26 '17 05:11

McKay


1 Answers

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.

like image 68
ivanl Avatar answered Oct 11 '22 22:10

ivanl