The issue I'm facing is best explained with the following example:
from abc import ABC, abstractclassmethod
from typing import Type
class SomeInterface(ABC):
"""Interface definition"""
@abstractclassmethod
def say_something(cls, stuff_to_say: str) -> None:
"""Some class method to be implemented"""
class TheImplementation(SomeInterface):
"""Implementation of above interface"""
@classmethod
def say_something(cls, stuff_to_say: str) -> None:
"""Implementation of class method in interface"""
print(stuff_to_say)
def do_something_with_type(input_class_type: Type[SomeInterface]) -> None:
"""Function that takes a class type as argument to call `say_something` on it"""
input_class_type.say_something("hi")
do_something_with_type(TheImplementation)
Note that the above code is valid Python, which executes and prints the right string "hi".
However, mypy
shows the following errors:
tests/annotation_test.py:28: error: Too few arguments for "say_something" of "SomeInterface"
tests/annotation_test.py:28: error: Argument 1 to "say_something" of "SomeInterface" has incompatible type "str"; expected "SomeInterface"
What am I doing wrong here? From reading the documentation I sense that input_class_type
argument to do_something_with_type
needs to be annotated differently but am not sure how exactly to go about this.
It looks like mypy doesn't understand abstractclassmethod
. Stacking classmethod
and abstractmethod
instead should work:
class SomeInterface(ABC):
@classmethod
@abstractmethod
def say_something(cls, stuff_to_say: str) -> None:
raise NotImplementedError
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments