Kay Schluehr wrote:

Why do You set

d.defaultValue(0)
d.defaultValue(function=list)

but not

d.defaultValue(0)
d.defaultValue([])

?

I think that's because you have to instantiate a different object for each different key. Otherwise, you would instantiate just one list as a default value for *all* default values. In other words, given:


class DefDict(dict):
    def __init__(self, default):
        self.default = default
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            return self.default

you'll get

In [12]: d = DefDict([])

In [13]: d[42].extend(['foo'])

In [14]: d.default
Out[14]: ['foo']

In [15]: d[10].extend(['bar'])

In [16]: d.default
Out[16]: ['foo', 'bar']

In [17]: d[10]
Out[17]: ['foo', 'bar']

In [18]: d[10] is d.default
Out[18]: True

and this isn't what you really wanted.

By the way, to really work, I think that Duncan's proposal should create new objects when you try to access them, and to me it seems a bit counterintuitive. Nevertheless, I'm +0 on it.

And why not dict(type=int), dict(type=list) instead where default
values are instantiated during object creation? A consistent pythonic
handling of all types should be envisioned not some ad hoc solutions
that go deprecated two Python releases later.

I don't really understand you. What should 'type' return? A callable that returns a new default value? That's exactly what Duncan proposed with the "function" keyword argument.


--
Ciao,
Matteo
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to