Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change __name__ atribute of object in python?

Tags:

python

object

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'
>>>
like image 327
rsk Avatar asked May 17 '11 16:05

rsk


People also ask

Can you write code to determine the name of an object in Python?

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.

Can you overwrite an object in Python?

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.

What is __ name __ in Python?

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.

Can the value of some objects change in Python?

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.


2 Answers

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.

like image 95
AJ. Avatar answered Oct 23 '22 10:10

AJ.


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.

like image 35
Nick Bailey Avatar answered Oct 23 '22 08:10

Nick Bailey