[Python-Dev] Dict suppressing exceptions

Guido van Rossum guido at python.org
Sat Aug 12 06:03:40 CEST 2006


On 8/11/06, Michael Chermside <mcherm at mcherm.com> wrote:
> Martin v. Löwis writes:
> > Now I looked at it, and think that the recipe is broken.
>
> Not broken, but perhaps wrongheaded. The recipe went out of its way
> to ensure that it would raise an exception of enum values from different
> enumerations were compared. There's nothing out there saying that this
> is a bad thing to do.

Except a little voice in my head. :-)

> I propose that we institute a new policy. The policy should state:
>
>     __eq__ methods should always return True or False. They should
>     only raise an exception if there is some internal error within
>     one of the objects being compared -- they should never raise
>     an exception because the other object is of an unexpected type.

That's pretty much what I want to do in py3k. There, ordering will
raise a TypeError by default, but == compares object identity by
default, and it's strongly recommended to return False for any
unrecognized type.

I want the recommendation to be a *little* more relaxed than your
proposal; IMO it's fine to raise an exception when your __eq__
implementation is incomplete, i.e. you haven't thought enough about
how your class should compare to other classes. The "don't silence
exceptions" rule will then cause loud complaints when your class gets
compared to something it didn't expect being compared to, signalling
that you have more work to do. (And yes, this can cause sleeper bombs
when you use these objects as dict keys together with types that it
doesn't understand, and the bomb will go off if there's a hash
collision; but I've got fairly controlled situations in mind, not
robust libraries or frameworks.)

>     On the other hand, __lt__, __gt__ and friends SHOULD raise an
>     exception when the object being compared is of some type for
>     which the ordering does not make sense (e.g.: unicode vs
>     byte-string or complex vs anything).

Yes, that's the py3k rule.

> I think we should note this policy someplace official -- perhaps
> in the Language Reference where __eq__ and __lt__ are defined. But
> I do not think that these changes should be made until Py3K.

Fine to update the docs now.

> What do others think? Is this the "right" approach?

Yes.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list