function parameter: question about scope
Alex Martelli
aleax at aleax.it
Sun Jul 14 12:40:09 EDT 2002
Uwe Mayer wrote:
> hi,
>
> I've got a object method which works similar to the __deepcopy__()
> function of the copy/deepcopy protocol. this function takes an optional
> argument "memo={}":
>
> def getElements(self, types, memo={}):
...
> Why does 'memo' keep exising?
What "keeps existing" is the DEFAULT value of memo -- it keeps
existing because it's stored among the function's attributes.
That's how default values of arguments behave: constructed once,
when you execute statement def, and thereafter remembered as
long as the function object survives.
This is generally OK when the default value is immutable, and
almost never what you want when it's mutable. Solution: don't
use mutable objects as default values for arguments. E.g., change
your function's start into:
def getElements(self, types, memo=None):
if memo is None: memo = {}
# proceed as before
This is the most idiomatic Python approach.
Alex
More information about the Python-list
mailing list