Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define function stubs enmasse

I have an object whose primary value is in applying a given decorator to every function it inherits from its super class and providing a separate version of it. For reference the decorator is below:

def hierarchywrapper(func):
    def wrapper(self, *args, **kwargs):
        for key, value in self.hierarchy.items():
            try:
                result = getattr(value, func.__name__)(*args, **kwargs)
                if result and len(result):
                    return result
                else:
                    pass
            except:
                pass
        return None
    return wrapper

The super class of the object containing this decorator has quite a few functions and I would prefer not to have to write out stubs for every one of them. As you can tell, the contents of these functions aren't very important and just need stubs really.

Is there some way to define function stubs en masse? Alternately is there some way I could indicate that I just want to apply this decorator to every inherited function?

like image 450
Slater Victoroff Avatar asked Dec 20 '25 16:12

Slater Victoroff


1 Answers

One way to do this would be to specialize the __getattribute__ method on your subclass:

def __getattribute__(self, name):
    attr = super(MySuperclass, self).__getattribute__(name)
    if callable(attr):
        return hierarchywrapper(attr)
    else:
        return attr

@eevee suggests an even more general approach by wrapping the parent object rather than subclassing it:

class CallableHierarchyWrapper(object):

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

    def __getattribute__(self, name):
        attr = self.wrapped_object.__getattribute__(name)
        if callable(attr):
            return hierarchywrapper(attr)
        else:
            return attr
like image 182
Peter DeGlopper Avatar answered Dec 22 '25 06:12

Peter DeGlopper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!