Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python's bools passed by value?

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?

like image 428
Geo Avatar asked Sep 29 '09 20:09

Geo


1 Answers

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).

like image 121
rcoder Avatar answered Sep 23 '22 19:09

rcoder