简体   繁体   English

装饰器/包装器:将位置/关键字args全部分配给包装函数的参数后,如何处理参数?

[英]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. 我想知道在Python中是否有一种方法可以让包装器在将函数的参数解析为参数后对其进行访问。 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: 对我的包装,看是否config并具有价值,如果没有,从别的地方加载它:

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. 但我不知道如何确定config是否已按位置传递,因为它在args列表中的位置因函数而异。

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. 如果我已经根据参数给位置参数指定了名称(例如,将第一个位置分配给a ,将第二个位置分配给b ,第三个位置分配给config ),然后可以保留这些参数那么我会答应。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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