I wrote the following code to check if integers are passed by value or reference.
foo = 1
def f(bar):
print id(foo) == id(bar)
bar += 1
print foo, b
The following happens:
print id(foo) == id(bar)
The identity is the same. print foo is bar
would have yielded the same, BTW.
bar += 1
This is translated to:
bar = bar.__iadd__(1)
And only if this does not work or does not exist, it calls:
bar = bar.__add__(1)
(I omit the case that bar = 1.__radd__(bar)
could as well be called.)
As bar
refers to a number, which is immutable, a different object is returned instead, so that bar
refers to 2
now, leaving foo
untouched.
If you do any of
print id(foo) == id(bar)
print foo is bar
now, you see that they now point to different objects.