How to get the formal args of a function object?
norseman
norseman at hughes.net
Thu May 14 17:41:24 EDT 2009
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?
>>
>> 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
=========================
Scott;
I'm lost with this.
If you use the same and add that it prints both the first_token/second
and the first_token multiplied by second and pass it (pi, 6, 7) what
happens then?
ie - function mysin only expects pi and 6 and is to print both pi/6 and
pi*6. The 7 is an error, not supposed to be there.
Steve
More information about the Python-list
mailing list