super().__init__(…) in mixins fails with `Too many

2019-05-23 20:53发布

When I create a mixin class that extends the logic of __init__, the regular thing to do is:

class ExtraValuemixin:

    def __init__(self, *args, **kwargs)  -> None:
        super().__init__(*args, **kwargs)
        # some extra initialization
        self._extra_value = 1

    def retrieve_extra_value(self):
        return self._extra_value

However this looks wrong to mypy, as it says:

Too many arguments for "__init__" of "object"

I get it, there's no *args or **kwargs in the object's constructor signature; but this is a mixin, and it relies on its childen's constructors. Ho do I make mypy understand this?

Full example:

class ExtraValuemixin:

    def __init__(self, *args, **kwargs)  -> None:
        super().__init__(*args, **kwargs)
        # some extra initialization
        self._extra_value = 1

    def retrieve_extra_value(self):
        return self._extra_value


class ParentObj:

    def __init__(self, value):
        self.value = value


class ChildObj(ExtraValuemixin, ParentObj):
    pass


obj = ChildObj(value=5)

print(obj.retrieve_extra_value())

标签: python mypy
0条回答
登录 后发表回答