How to get the formal args of a function object?
Scott David Daniels
Scott.Daniels at Acm.Org
Thu May 14 16:42:16 EDT 2009
kj wrote:
> Suppose that f is an object whose type is 'function'.
>
> Is there a way to find out f's list of formal arguments?
>
> The reason for this is that I'm trying to write a decorator and
> I'd like the wrapper to be able to check the number of arguments
> passed....but I'm missing something like the hypothetical attribute
> FORMAL_ARGS above.
I can write a wrapper now:
def tracer(function):
def internal(*args, **kwargs):
print('calling %s(%s)' % (function.__name__,
', '.join([repr(arg) for arg in args] +
['%s=%r' % ka for ka in sorted(kwargs)])))
result = function(*args, **kwargs)
print('=> %r' % result)
return internal
and call like so:
tracer(math.sin)(3.1415 / 6)
calling sin(0.5235833333333334)
=> 0.49998662654663256
What would your missing something be for tracer(math.sin)?
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list