[issue9702] Python violates most users expectations via the modification differences of immutable and mutable objects in methods

Theo Julienne report at bugs.python.org
Sat Aug 28 01:10:13 CEST 2010


Theo Julienne <theo.julienne at gmail.com> added the comment:

def list_again(foo):
	foo.append("bar")

def list_again_again(foo):
	foo = foo + ["1"]


The part that can be confusing is that 'foo' is a *copy* of a *reference* to an object. Because 'foo' is a copy, assigning to it will only alter a local copy, while calling methods on it will always call on the original object (because it's a reference to the same place). When an object is mutable, it just has no methods that modify it, so the only way to change it is by assignment, which will never result in changes to the outside function. There are no special cases, but it does require understanding pass-by-(copy/reference) and object mutability, and is against most people's intuitions.

The way that behaves is actually how most *programmers* would expect (because they are used to it), though. Every other language I can think of does it this way. For example, in C, a pointer is still a copy of a reference -- if you assign to the pointer, it wont propagate up to the caller. The same goes in Java.

Perhaps what makes it harder to understand in Python is that everything is an object and looks the same regardless of mutability, whereas other languages typically have conventions (such as capitalising: int, str, Dict, List) to make it clearer when something is an object (which usually means the same as a python mutable object) as opposed to a built-in type (which usually means the same as a python immutable object).

Just my 2c

----------
nosy: +Theo.Julienne

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9702>
_______________________________________


More information about the Python-bugs-list mailing list