Local variables persist across function calls

Alf P. Steinbach alfps at start.no
Sat May 15 13:56:33 EDT 2010


On 15.05.2010 19:18, * Dave:
> I've been writing Python for a few years now, and tonight I ran into
> something that I didn't understand. I'm hoping someone can explain
> this to me. I'm writing a recursive function for generating
> dictionaries with keys that consist of all permutations of a certain
> set. Here's the function:
>
> <code>
> def make_perm(levels, result = {}, key = ''):
> 	local = key
> 	if levels == 1:
> 		for i in ['a', 'b', 'c', 'd']:
> 			result [local + i] = ''
> 	else:
> 		for i in ['a', 'b', 'c', 'd']:
> 			make_perm(levels - 1, result, local + i)
> 	return result
> </code>

I bet this is a FAQ, but I don't know where the FAQ is (probably at python.org?).

The defaults for formal parameters are evaluated /once/, namely at function 
definition time, when the execution first passes through the definition.

And what you're doing is to update that original default 'result' dictionary.

To achieve the effect that you apparently want you can do


   def make_perm( levels, result = None, key = '' )
       if result is None: result = {}  # Evaluated for each call.
       # Blah blah, the rest


There are also other ways.


Cheers & hth.,

- Alf

-- 
blog at <url: http://alfps.wordpress.com>



More information about the Python-list mailing list