Is it correct to change the value of __name__
atribute of object like in the following example:
>>>
>>> def f(): pass
...
>>> f.__name__
'f'
>>> b = f
>>> b.__name__
'f'
>>> b.__name__ = 'b'
>>> b
<function b at 0x0000000002379278>
>>> b.__name__
'b'
>>>
No, there's no way to discover the name of an object in Python. The reason is that the objects don't really have names.
In python what we call variables are really labels referring to objects. So if you want to change an object that is not immutable (like a list), that should work out-of-the-box in Python. However, you cannot really generally overwrite objects in Python. Creating a new object will use free memory.
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.
Changing a function's name doesn't make the new name callable:
>>> def f(): print 'called %s'%(f.__name__)
...
>>> f()
called f
>>> f.__name__ = 'b'
>>> f()
called b
>>> b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
You'd have to define b
in order to call it. And as you saw, simply assigning b=f
doesn't define a new function.
Yes, you can change __name__
. I sometimes change the __name__
of a decorator instance to reflect the function it's decorating, e.g.
class CallTrace:
...
def __init__(self, f):
self.f = f
self.__name__ = f.__name__ + ' (CallTraced)'
I'm not asserting this is good practice, but it has helped me debug code in the past. The idea is if you decorate a function fn
, then type fn.__name__
at the prompt, you can see immediately that it's decorated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With