Puzzling: local variable in recursive function made global?

andrew cooke andrew at acooke.org
Thu Mar 26 18:09:23 CET 2009


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.

andrew





More information about the Python-list mailing list