3

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the id built-in is indeed the correct way to show that the renamed function references the same object. Thanks.
3
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}

1 Comment

Good to know that this is where the attributes go, into the dict. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.