Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading