简体   繁体   中英

Decorator/wrapper: How to deal with arguments after positional/keyword args are all assigned to wrapped function's parameters?

I'm wondering if there's a way in Python for a wrapper to get access to a function's arguments after they've already been resolved into parameters. So for instance, I'd like to wrap two functions that have different (numbers of) parameters:

def fn_1(a, b=None, config=None):
    ...

def fn_2(b=None, config=None):
    ...

I'd like for my wrapper to see if config has a value and, if not, to load it from somewhere else:

class with_config(object):
    def __init__(self, f):
       self.f = f
    def __call__(self, *args, **kwargs):
       if config not in kwargs:
           kwargs[config] = load_config_from_some_default_location()

but I don't know how to determine if config has been passed positionally, as its position in the args list can vary from function to function.

If I could get ahold of the arguments after the positional ones have been given names according to the parameters (eg first positional assigned to a , second to b , third to config ) I'd be A-OK.

The situation is slightly more complex than this but I think this gets my question across.

Any tips?

This may help you:

import inspect

def func(a, b=None, config=None):
    args, _, _, values = inspect.getargvalues(inspect.currentframe())
    print args # prints 'a', 'b', 'config'
    print values # prints {'a':12, 'b':None, 'config':None}
    if values['config'] == None:
        # Load config from somewhere else

if __name__ == '__main__':
    func(12)

我终于从Nadia Alramli那里得到了这个解决方案

class with_config(object): def __init__ (self, f): self.f = f def __call__ (self, *args, **kwargs): kwargs.update(dict(zip(self.f.func_code.co_varnames, args))) if config not in kwargs: kwargs[config] = load_config_from_some_default_location() return self.f(**kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM