You are on page 1of 4

The term shared reference is the concept of two variables referencing

the same object in memory (i.e. having the same memory address)

0x1000
a = 10 a 10
b = a
b

def my_func(v): 0x2000


… t 20
t = 20 v
my_func(t)
In fact, the following may surprise you:

0x1000
a = 10 a 10
b = 10
b

0x23FA
s1 = ‘hello’ s1 hello
s2 = ‘hello’
s2

In both these cases, Python’s memory manager decides to automatically re-use


the memory references!! We’ll revisit this again soon

Is this even safe? Yes


The integer object 10, and the string object ‘hello’ are immutable
– so it is safe to set up a shared reference
When working with mutable objects we have to be more careful

1 0x1000
a = [1, 2, 3] a 2
b = a 3
b 100
b.append(100)

With mutable objects, the Python memory manager will never create shared references

1 0x1000
a = [1, 2, 3] a 2
b = [1, 2, 3] 3

1 0xF354
b 2
3

You might also like