Puzzling: local variable in recursive function made global?

Peter Otten __peter__ at web.de
Thu Mar 26 19:29:48 CET 2009

andrew cooke wrote:

> Diez B. Roggisch wrote:
>> That's not a local variable, that is a default argument. Which is in
>> fact only created once for each function, yes.
>> http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm
> a nice way of handling this was posted here just yesterday, which isn't in
> the ffbot page (afaik):
>   def function(listvar=None):
>     # None will force use of empty list here:
>     for x in listvar or []:
>       # Do soemthing with contents here
> or just
>   def function(listvar=None):
>     listvar = listvar or []
>     ...
> although the "if arg is None..." is pretty standard python that makes it
> clear exactly what you are doing.

Plus, it works as expected (read: modifies the argument) if you explicitly
pass an empty list to the function...


More information about the Python-list mailing list