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

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


class ModelBase(object):

    @classmethod
    def method_one(cls, *args):
        raise NotImplementedError

    @classmethod
    def method_two(cls, *args):
        return cls.method_one(*args) + 1

    def __getattribute__(self, attr):
        value = object.__getattribute__(self, attr)
        if attr == 'method_two':
            value = copy_signature(frm=self.method_one, to=value)
        return value


class SubClass(ModelBase):
    @staticmethod
    def method_one(a, b):
        return a + b


class SubClass2(ModelBase):
    @staticmethod
    def method_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?"