strange behaviour with keyword arguments and inheritance

Arnaud Delobelle arnodel at googlemail.com
Tue Apr 17 05:16:22 EDT 2007


matthewperpick wrote:
> Check out this toy example that demonstrates some "strange" behaviour
> with keyword arguments and inheritance.
>
> =================================
>
> class Parent:
>     def __init__(self, ary = []):
>         self.ary = ary
>
[snip]

As pointed out earlier, default values for arguments are evaluated
when the function is defined, not when it is called.  This creates
confusion if this value is mutable and later mutated; I got confused
by it when I started python.  So it is often not a good idea to use
mutable objects as default arguments.

A simple fix:

def __init__(self, ary=None):
    if ary is None: ary = []
   self.ary = ary

--
Arnaud




More information about the Python-list mailing list