Search code examples
pythonpython-3.xfunctionpython-decoratorsinspect

Capturing a function call as dict


I'm trying to write a python function decorator, and part of my implementation is that I need to capture the function call and look through the supplied values. I already have the function signature by using inspect.signature, but I'm unsure how to compose it with passed arguments.

Say I had the following

def decorator(func):
    def wrapper(*args, **kwargs):
        print(some_function_signature_getter(func, *args, **kwargs))
        return func(*args, **kwargs)
    return wrapper


@decorator
def foo(a, b, *_, **kwargs):
    return a+b

print(foo(1, 2))

How can I implement some_function_signature_getter such that my output is something like the following:

{'a': 1, 'b': 2, '_':[], 'kwargs':{}}
3

Solution

  • Whenever you want to introspect function/method signatures, you can use inspect.signature. In this case:

    from inspect import signature
    
    def decorator(func):
        sig = signature(func)
        def wrapper(*args, **kwargs):
            bound = sig.bind(*args, **kwargs)
            bound.apply_defaults()
            print(bound.arguments)
            return func(*args, **kwargs)
        return wrapper
    

    *args are a tuple, not a list, but otherwise this gives you what you want:

    >>> print(foo(1, 2))
    {'a': 1, 'b': 2, '_': (), 'kwargs': {}}
    3