Rant (was Re: x*x if x>10

Diez B. Roggisch deets at nospam.web.de
Sun Jul 27 13:46:32 EDT 2008


> 
>> Can you tell us what you mean by "several names of one object"? You mean 
>> this?
>>
>> a = range(10)
>> b = a
>>
>> id(a) == id(b)
>>
>>
>> ? Passing references instead of values is an extremely important concept 
>> of many languages, without it you would end up copying most of the time.
> 
> OK. I've obviously been thinking about things the wrong way. In Forth you
> pass the memory address around, and presumably that's essentially what's
> happening when you pass a reference.

Pretty much, yes. And I for once can say that I've been caught by 
modifying e.g. stack-locals instead of heap-objects in C++ by accident.


> The problem is, I get caught frequently
> in this situation:
> 
> a = [1,2,3]
> 
> def foo(x):
> 	do_something_with_x
> 	return x
> 
> ...
> 
> Then when I call foo(a), a gets changed. It just isn't the effect I expect
> from changing a local.

It's the way things work - mutables are mutables. If you want them to be 
modified, use the module copy.

As a rule of thumb, don't return objects you didn't create inside a 
function from scratch.

Which is the exact reasoning for the

list.sort

method btw - returning None is supposed to make you aware of the 
in-place modification.




Diez



More information about the Python-list mailing list