Skip to content Skip to sidebar Skip to footer

How To Dynamically Change Signatures Of Method In Subclass?

When using classmethod to dynamic change the method in subclass, how to dynamic change signatures of method? example import inspect class ModelBase(object): @classmethod

Solution 1:

If this is only for introspection purpose you could override __getattribute__ on ModelBase and every time method_two is accessed we return a function that has the signature of method_one.

import inspect

defcopy_signature(frm, to):
    defwrapper(*args, **kwargs):
        return to(*args, **kwargs)
    wrapper.__signature__ = inspect.signature(frm)
    return wrapper


classModelBase(object):

    @classmethoddefmethod_one(cls, *args):
        raise NotImplementedError

    @classmethoddefmethod_two(cls, *args):
        return cls.method_one(*args) + 1def__getattribute__(self, attr):
        value = object.__getattribute__(self, attr)
        if attr == 'method_two':
            value = copy_signature(frm=self.method_one, to=value)
        return value


classSubClass(ModelBase):
    @staticmethoddefmethod_one(a, b):
        return a + b


classSubClass2(ModelBase):
    @staticmethoddefmethod_one(a, b, c, *arg):
        return a + b

Demo:

>>>test1 = SubClass()>>>print(inspect.signature(test1.method_two))
(a, b)
>>>test2 = SubClass2()>>>print(inspect.signature(test2.method_two))
(a, b, c, *arg)

Post a Comment for "How To Dynamically Change Signatures Of Method In Subclass?"