newbie questions

Steven Bethard steven.bethard at gmail.com
Sat Dec 11 14:47:56 EST 2004


houbahop wrote:
> Hello again everyone ,
> var2[:]=[] has solved my problem, and I don't understand why it is 
> programming by side effect.
> I don't think it's bad, look at this, it's what I've done :
> 
> def Clear(lvar)
>     lvar[:]=[]
> 
> def main (starting class)
>    var1=[]
>    var1.append('a')
>    Clear(var1)

 From http://en.wikipedia.org/wiki/Side-effect_(computer_science)

In computer science, a side-effect is a property of a programming 
language function that it modifies some state other than its return value.

Given this definition, I think you're fine -- clearing the list isn't a 
side effect of the function; it is the purpose of the function.  Hence 
the function has no return value.[1]



Of course, in this simple case, I wouldn't be likely to write the clear 
function since the inline code is simpler and has less overhead:

def main()
     var1 = []
     var1.append('a')
     var1[:] = []

or, since in this case, you only care about var1, you can just rebind it 
(and let Python garbage-collect the old list):

def main()
     var1 = []
     var1.append('a')
     var1 = []

Steve

[1] Technically, all Python functions without a return statement return 
None, but for our purposes, we can consider a function like this to have 
"no return value".



More information about the Python-list mailing list