Python 3.6: Signature of {method} incompatible with super type {Class}
While trying to update my code to be PEP-484 compliant (I'm using mypy 0.610) I've ran into the following report:
$ mypy mymodule --strict-optional --ignore-missing-imports --disallow-untyped-calls --python-version 3.6
myfile.py:154: error: Signature of "deliver" incompatible with supertype "MyClass"
MyClass:
from abc import abstractmethod
from typing import Any
class MyClass(object):
@abstractmethod
def deliver(self, *args: Any, **kwargs: Any) -> bool:
raise NotImplementedError
myfile.py:
class MyImplementation(MyClass):
...
def deliver(self, source_path: str,
dest_branches: list,
commit_msg: str = None,
exclude_files: list = None) -> bool:
...
return True
I'm definitely doing something wrong here, but I can't quite understand what :)
Any pointers would be much appreciated.
Mypy is basically reporting that your classes aren't respecting the Liskov substitution principle.
Basically, the issue is what happens if somebody tries doing this?
def accepts_myclass(obj: MyClass):
# MyClass.deliver accepts any arbitrary arg and kwargs, so surely this should be legal?
obj.deliver(foobar=3)
# MyImplementation is a subtype of MyClass, so this is legal, right?
accepts_myclass(MyImplementation())
This all typechecks but will actually result in a crash at runtime.
To fix this, you need to...
- Make sure
MyImplementation.deliver(...)can accept anythingMyClass.deliver(...)can accept and - Make sure
MyImplementation.deliver(...)doesn't return anything somebody callingMyClass.deliver(...)can't handle.
To satisfy criteria 1, you can either make MyImplementation also accept arbitrary args/kwargs, or modify MyClass so the signature doesn't accept anything a subclass can't handle. You've already handled criteria 2, since both functions are returning the same type.
Hi @Michael0x2a, thanks so much for your quick response and great explanation. That makes a lot of sense!
I've also tried
def deliver(self, source_path: str,
dest_branches: list,
commit_msg: str = None,
exclude_files: list = None,
*args: Any, **kwargs: Any
)
To comply with criteria 1 (which I kinda guessed while trying different things), but that doesn't look to be the right way, isn't? I'm still getting the same report error.
I think there, the issue is that according to the signature of MyClass, the following would be legal: obj.deliver(source_path=3). We'd run into the same kind of runtime issue though.
Hi @Michael0x2a, thanks again for your reply.
I understand this is not the place to post my kind of issue (this is just a misunderstanding on how to implement this on my side, and not a typing lib issue), so I've moved my question to https://stackoverflow.com/questions/51003146/python-3-6-signature-of-method-incompatible-with-super-type-class/51003172 so I don't fill this repo with noise :)