Inconsistency in dictionary behaviour: dict(dict) not calling __setitem__

Andrea Griffini agriff at tin.it
Tue Dec 12 19:37:52 EST 2006


Mitja Trampus wrote:

...
> At least, I know it surprised me when I first met this behavior. Or is 
> my reasoning incorrect?

Why len() doesn't call iteritems() ? :-)

Kidding apart for example it would be ok for __setitem__
to call either an internal "insert_new_item" or
"update_existing_item" depending on if the key is
already present in the dictionary.
In this case I suppose you agree it would make a lot
of sense to go directly for "insert_new_item" in the
constructor from a dict instead of calling the public
__setitem__...

The key point is that you're not authorized to assume
constructing a dictionary from a dictionary will use
__setitem__ unless this is explicitly stated in the
interface.

...

> What I find an even nastier surprise is that dict.update behaves this 
> way as well:
...
> The docstring is, at best, misguiding on this particular point:
> 
>  >>> print d.update.__doc__
> D.update(E, **F) -> None.  Update D from E and F: for k in E: D[k] = E[k]
> (if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = 
> F[k]

I cannot understand this doc string at all.

The explanation in the manual however just talks about
"updating", with no reference to assignments. The manual
of 2.3 instead was using a code example and I'd say this
would qualify as a binding to actually implement calls
to __setitem__. This kind of error (i.e. over-specifying
by providing actual code that implies specific side-effects)
was also present in the C++ standard, and in at least
one case an implementation would have to be very
inefficient to comply on the issue (this fortunately is
not what happened, the standard was "fixed" instead).

If there is a bug in this case is IMO a docstring bug.

Andrea



More information about the Python-list mailing list