I'm using the decorator module to decorate some functions. I want the decorator to be quite general, so I'm allowing it to have any number of arguments and keyword arguments (as long as there are more than two arguments):
from decorator import decorator
def wrap(f):
return decorator(_wrap, f)
def _wrap(function, t, f, *args, **kwargs):
开发者_开发知识库 print 't=', t
print 'f=', f
print 'args=', args
print 'kwargs=', kwargs
@wrap
def read(a, b, c=False, d=True):
pass
read(1, 2, d=True)
The issue is that the above return:
t= 1
f= 2
args= (False, True)
kwargs= {}
but the False
and True
come from c=
and d=
, so shouldn't they be in kwargs
, i.e.:
t= 1
f= 2
args= (,)
kwargs= {'c':False, 'd':True}
?
c
and d
are positional arguments. Their names are included in the function object's metadata (because you use decorator
, it's also preserved on the wrapper) and therefore you can refer to their names when calling the function, but they're still positional arguments and specifying them by their names merely leads to them being put into the correct positions in args
. And it works as expected, so why is it an issue?
Just in case, check this other post talking about the same issue decorator python library hide the kwargs inside args (and giving the same answer as delnan)
精彩评论