遵循此主题:allow users to "extend" API functions
class Inspector:
def __init__(self, passedFunc):
self.passedFunc = passedFunc
def __call__(self, *args, **kwargs):
# Inspector needs to generate a list of arguments of the passed function and print them in *correct* order
# now how to generate a list of arguments using data from both ''args' and 'kwargs'?
# the user might keep default argument values, in which case both will be None,
# he might only use args, in which case it is easy,
# but he might also use kwargs, in which case I don't see how to generate a list with correct order of arguments
# and he might use all 3 from above together
# I found this solution for when only default arguments are used
if args == () and kwargs == {}: args = self.passedFunc.__defaults__
print args
@Inspector
def exampleFunc(value=0, otherValue=3):
pass
exampleFunc()
如何为所有方案生成正确的订单参数列表?
最佳答案
这是在装饰器中构建实际参数列表的方式:
import inspect
class Inspector:
def __init__(self, passedFunc):
self.passedFunc = passedFunc
def __call__(self, *args, **kwargs):
spec = inspect.getargspec(self.passedFunc)
params = dict(zip(spec.args, args))
defaults = dict(zip(spec.args[-len(spec.defaults):], spec.defaults))
for k, v in kwargs.items():
if k not in spec.args:
raise TypeError('unexpected argument', k)
if k in params:
raise TypeError('mulitple values for argument', k)
params[k] = v
for k in spec.args:
if k not in params:
if k in defaults:
params[k] = defaults[k]
else:
raise TypeError('missing argument', k)
args_in_order = [params[x] for x in spec.args]
print args_in_order
例:
@Inspector
def exampleFunc(value=0, otherValue=3):
pass
exampleFunc() # 0,3
exampleFunc('foo') # foo,3
exampleFunc(otherValue='foo', value=555) # 555,foo