I'm trying to write an abstract class with unimplemented methods, which will force the inheriting children to return a value of a specific type when they override the method (defined in the decorator).
When I use the code shown below, the child method does not call the decorator. I assume this is because the method is being overridden, which makes a lot of sense. My question is basically this: Is there a way to make a decorator persist through method overriding?
I'm not opposed to using something other than a decorator, but this was a solution that quickly popped to mind and I'm curios to know if there's any way to make it work.
In case going with a decorator is the correct and possible choice, it will look something like this:
def decorator(returntype):
def real_decorator(function):
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
if not type(result) == returntype:
raise TypeError("Method must return {0}".format(returntype))
else:
return result
return wrapper
return real_decorator
I need my parent class to look similar to this one:
class Parent(ABC):
@decorator(int)
@abstractmethod
def aye(self, a):
raise NotImplementedError
And the child class will do something of this sort:
class Child(Parent):
def aye(self, a):
return a
I'd be more than happy to clarify my question better if needed, and thank you to everyone who takes the time to read this question in advance!
def aye(self, a): res = self._aye(a) assert isinstance(res, int) return res
where_aye
is the actual method on subclasses andaye
is its public, type-checking invocator? – ExpanseParent
class as you have to implement a method with an other name than the actual method that is called). Well, I'm nitpicking, it also does the job in the end ! – Mapping