Python Forum

Full Version: Passing an argument by reference
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I tried out like this
class Spam:
    pass
def fun(a):
    a.foo=5
    print(a.foo)
    print(id(a.foo))

foo=6
id1=5
s=Spam()
fun(s)
print(s.foo)
print(foo)
print(id(foo))
print(id1)
print(id(id1))
And the output is
Output:
5 1918656864 5 6 1918656896 5 1918656864
Interesting.. looks like the same memory reference for value 5 is being shared by both variables a.foo and id1
Malt Wrote:looks like the same memory reference for value 5 is being shared by both variables a.foo and id1
Yes, python keeps an array of instances for the small integers and reuses them. See here. This is an implementation detail.
λ python                                                                                          
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32 
Type "help", "copyright", "credits" or "license" for more information.                            
>>> hash(2)                                                                                       
2                                                                                                 
>>> hash(1)                                                                                       
1                                                                                                 
>>> hash(0)                                                                                       
0                                                                                                 
>>> hash(-1)                                                                                      
-2                                                                                                
>>> hash(-2)                                                                                      
-2                                                                                                
>>> hash(-3)                                                                                      
-3                                                                                                
>>>                                                                                               
If you check values for equality, don't use identity checks (is/is not). Use equality check for integers and comparison for floats.
If you want to check for Types of objects, which exists only once in memory, it's save to use the is operator.

*to check floats of equality, use math.isclose.
Pages: 1 2