How to get the formal args of a function object?

Scott David Daniels Scott.Daniels at Acm.Org
Fri May 15 01:43:21 CEST 2009

norseman wrote:
> Scott David Daniels wrote:
>> 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?...
>> 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;
> I'm lost with this.

Sorry, I was too telegraphic.  I was pointing out that my wrapper
function (and, indeed, lots of Python code) does something and
passes along whatever args it got.  It's obvious tracer takes a
single arg, but, tracer(math.sin) takes a single arg, while
tracer(math.atan2) takes two args.  If what your code gets is
one of these wrapped functions, it will be tricky to figure out
what the eventual arg list needed will be.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list