I sent a reference to a bool object, and I modified it within a method. After the method finished its execution, the value of the bool outside the method was unchanged.
This leads me to believe that Python's bools are passed by value. Is that true? What other Python types behave that way?
Python variables are not "references" in the C++ sense. Rather, they are simply local names bound to an object at some arbitrary location in memory. If that object is itself mutable, changes to it will be visible in other scopes that have bound a name to the object. Many primitive types (including bool
, int
, str
, and tuple
) are immutable however. You cannot change their value in-place; rather, you assign a new value to the same name in your local scope.
In fact, almost any time* you see code of the form foo = X
, it means that the name foo
is being assigned a new value (X
) within your current local namespace, not that a location in memory named by foo
is having its internal pointer updated to refer instead to the location of X
.
*- the only exception to this in Python is setter methods for properties, which may allow you to write obj.foo = X
and have it rewritten in the background to instead call a method like obj.setFoo(X)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With