2

Say I have an abstract class:

class A(metaclass=ABCMeta):

    def __init__(self):
        pass

    @abstractmethod
    def a_function(self) -> int:
        return 0

I want to constrain the type of the output of a_function so that when a class inherits from A the output has to be an integer.

My first attempt was to make a decorator for a_function of class A (see below). But of course it only constrains A.a_function

def constrain_type(f):
    def decorated(*args, **kwargs):
        output = f(*args, **kwargs)
        class_annotation = f.__annotations__["return"]
        if not issubclass(type(output), class_annotation):
            raise TypeError("this class must return an object inheriting from " +
                            class_annotation.__name__ + " not " + type(output).__name__)

        return output
    return decorated
dallonsi
  • 1,299
  • 1
  • 8
  • 29

0 Answers0