Wednesday, 3 February 2021

Copying function signature in a method

I am trying to create a function Bar.bar with signature and docs copied (OP) from foo:

from inspect import signature
import functools
from typing import Callable

def deco_meta_copy_signature(signature_source: Callable):
    def deco(target: Callable):
        @functools.wraps(target)
        def tgt(*args, **kwargs):
            signature(signature_source).bind(*args, **kwargs)
            return target(*args, **kwargs)
        tgt.__signature__ = signature(signature_source)
        tgt.__doc__ = signature_source.__doc__
        print('Signature 1)', signature(tgt))
        return tgt
    return deco

def foo(a, b, c=0, d=1, **kwargs):
    """ foo! """
    pass

class Bar:
    @deco_meta_copy_signature(foo)
    def bar(self):
        pass

b = Bar()
print('Signature 2)', signature(b.bar))

which prints:

Signature 1) (a, b, c=0, d=1, **kwargs)
Signature 2) (b, c=0, d=1, **kwargs)

As you can see in Signature 2 the first parameter is not preserved. I assume this has to do with the target function being a method and receiving self parameter. How can I add self to the signature while having all the other parameters as well?



from Copying function signature in a method

No comments:

Post a Comment