Reputation: 83
I want to use function attributes to set variable values as an alternate to using global variables. But sometimes I assign another short name to a function. The behavior seems to always do what I want, i.e. the value gets assigned to the function whether I use the long or short name, as shown below. Is there any danger in this?
def flongname():
pass
f = flongname
f.f1 = 10
flongname.f2 = 20
print flongname.f1, f.f2
And the last line returns 10 20
showing that the different function names refer to the same function object. Right?
Upvotes: 3
Views: 124
Reputation: 14854
f = flongname # <- Now f has same id as flongname
f.f1 = 10 # <- a new entry is added to flongname.__dict__
flongname.f2 = 20 # <- a new entry is added to flongname.__dict__
print flongname.f1, f.f2 # Both are refering to same dictionary of the function
looking it as it is is doesn't seems dangerous, just remember nobody else is modifying its dict
In [40]: f.__dict__
Out[40]: {}
In [41]: flongname.__dict__
Out[41]: {}
In [42]: f.f1=10
In [43]: flongname.__dict__
Out[43]: {'f1': 10}
In [44]: f.__dict__
Out[44]: {'f1': 10}
In [45]: flongname.f2 = 20
In [46]: f.__dict__
Out[46]: {'f1': 10, 'f2': 20}
Upvotes: 3
Reputation: 19325
id
shows that the both f
and flongname
are references to the same object.
>>> def flongname():
... pass
...
>>> f = flongname
>>> id(f)
140419547609160
>>> id(flongname)
140419547609160
>>>
so yes- the behavior you're experiencing is expected.
Upvotes: 5