class constructors: class vs. instance defaults

exarkun at divmod.com exarkun at divmod.com
Thu Oct 7 01:17:05 CEST 2004


On Wed, 6 Oct 2004 20:10:52 -0300, Carlos Ribeiro <carribeiro at gmail.com> wrote:
>On Wed, 6 Oct 2004 16:39:50 -0600, Erik Johnson <ej
> <at at bag.python.org>wellkeeper <"dot>com"@bag.python.org> wrote:
> [snip]
> 
> That's it, in a nutshell.
>  
> > class Bar:
> > 
> >     def __init__(self, foo_d=None)
> >         if foo_d:
> >             self.foo_d = foo_d
> >         else:
> >             self.foo_d = {}
> 
> Well, it works. I don't see anything wrong with it. Youonly need to
> take care with objects that are mutable. This includes lists and
> dicts, but _not_ ints, floats or strings. These you can use as
> defaults just fine, without fear.
> 
> ... but you can try this code also:
> 
> self.foo_d = foo_d or {}

  One could argue that there is something slightly wrong with both of these.  Consider:

    d = {}
    b = Bar(d)
    d['x'] = 'y'

  One might reasonably expect b.foo_d['x'] to be 'y'.  In the case of the above, it will not be; a KeyError will be raised instead.  A better way, IMHO, to write the above idea is this:

    class Foo:
        def __init__(self, foo_d=None):
            if foo_d is None:
                foo_d = {}
            self.foo_d = foo_d

  Jp



More information about the Python-list mailing list