On 2011-05-31, at 24:35 , Dan Stromberg wrote:

> 
> On Mon, May 30, 2011 at 5:28 PM, Henry Olders <henry.old...@mcgill.ca> wrote:
> 
> Be careful not to conflate global scoping or global lifetime, with mutability 
> or pure, side-effect-free functions (callables).  It sounds like what you 
> want is immutability and/or freedom from side effects, which is found most 
> often in (pure) functional languages - which is not what Python is, nor does 
> it attempt to be so.

I think you're right, I've been conflating scoping with side effects caused by 
passing mutable objects. 
> 
> In Python, and in many other languages, if you pass a scalar (or more 
> generally, an object of an immutable type) to a function, and then change the 
> scalar in that function, you only change the scalar within that function, not 
> within the caller.
> 
> However, if you pass an aggregate type like a list (array) or dictionary 
> (hash table), then the formal argument itself that you've passed is still 
> only changeable within that function, however what it points off at _is_ 
> changeable via that formal argument.  This is of course because otherwise 
> passing a 1 gigabyte dictionary to a function would either have to copy the 
> whole dictionary, or implement some sort of Copy-on-Write semantics, or make 
> it somehow readonly.
> 
> If you need side effect-free functions in Python, you'd probably best copy 
> your aggregates, EG:
> 
> import copy
> 
> def main():
>       a = ['a list','with','three elements']
>       print a
>       print fnc1(a)
>       print a
> 
> def fnc1(b):
>       b = copy.deepcopy(b)
>       return fnc2(b)
> 
> def fnc2(c):
>       c = copy.deepcopy(c)
>       c[1] = 'having'
>       return c

Clearly, making a copy within the function eliminates the possibility of the 
side effects caused by passing in mutable objects. Would having the 
compiler/interpreter do this automatically make python so much different? What 
if it were optional, like nested scopes were in python 2.1 until they became 
standard in 2.2?

Henry
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to