Simulated Pointers With Mutable Types
In this lesson, you’ll simulate pointer behavior in Python using a mutable object type. This is not actual pointer behavior. These operations are more memory expensive than they would be in C.
00:00
I’m here in a new Python script within Visual Studio Code and I’m going to start by defining a new name called y
and pointing it at a list containing the value 2337.
00:14
I’m going to use the mutable list to modify the value of the immutable integer inside of it. To do that, I’ll define a new function called add_one()
, which will take in some list and add 1 to the value inside of it.
00:32 I will call this function and print the value of the integer inside the list.
00:41 It looks like things worked as expected. We incremented the value inside the list by 1. But is this any more memory efficient? Not really. We simulated pointer behavior by passing the function an object it could mutate directly, but it still had to increment the immutable type inside the object.
01:03 We’ve merely simulated a pointer without the efficiency benefits of one. We can achieve similar results with other mutable types, too.
01:14
This file here uses a dictionary, instead. This foo()
function here increments the counter by 1, then calls the bar()
function. It too increments the counter by 1.
01:28 Then, we print the value of the counter, which should be 2.
carl on July 15, 2020
Taking that one step further, if we now define a function to reset both coordinates of a Point, we’ll see that it’s still mutating p. This is pass-by-assignment in action.
def reset(q):
q.set_x(0)
q.set_y(0)
p = Point(1, 1)
print(id(p), p)
reset(p)
print(id(p), p)
Become a Member to join the conversation.
carl on July 15, 2020
I think that it would have been very instructive, as your second example, to point out that objects of classes that you create can also be mutable. A simple type like this mutable Cartesian Point class illustrates the same concept I think you were making with your second example, but is less complicated
If we run this we see that the name p refers to the same object the entire time, but because we exposed those set methods, we can mutate its state. The names
self._x
orself._y
will point to different (immutable) values after one of the set methods is used, effectively changing the mutable state of p.