Function name unchanged in error message

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Fri Jan 29 09:50:34 EST 2010


On 02:10 pm, clp2 at rebertia.com wrote:
>On Fri, Jan 29, 2010 at 5:30 AM, andrew cooke <andrew at acooke.org> 
>wrote:
>>Is there any way to change the name of the function in an error
>>message?  In the example below I'd like the error to refer to bar(),
>>for example (the motivation is related function decorators - I'd like
>>the wrapper function to give the same name)
>>>>>def foo():
>>...     return 7
>>...
>>>>>foo.__name__ = 'bar'
>>>>>foo(123)
>>Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>>TypeError: foo() takes no arguments (1 given)
>
>It gets weirder:
>>>>print(foo)
><function bar at 0x37b830>

The name is represented in (at least) two places, on the function object 
and on the code object:

    >>> def foo(): pass
    ...    >>> foo.func_name
    'foo'
    >>> foo.func_code.co_name
    'foo'
    >>> foo.func_name = 'bar'
    >>> foo
    <function bar at 0xb74f2cdc>
    >>> foo.func_code.co_name = 'baz'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: readonly attribute
    >>>
new.function and new.code will let you construct new objects with 
different values (and copying over whichever existing attributes you 
want to preserve).

Jean-Paul



More information about the Python-list mailing list