list equal to subclass of list?

Eric Snow ericsnowcurrently at gmail.com
Thu May 12 11:30:19 EDT 2011


On Thu, May 12, 2011 at 6:23 AM, Roy Smith <roy at panix.com> wrote:

> I have a vague feeling this may have been discussed a long time ago, but
> I can't find the thread, so I'll bring it up again.
>
> I recently observed in the "checking if a list is empty" thread that a
> list and a subclass of list can compare equal:
>
> ----------------------------
> class MyList(list):
>    "I'm a subclass"
>
> l1 = []
> l2 = MyList()
>
> print type(l1), type(l2)
> print type(l1) == type(l2)
> print l1 == l2
> ----------------------------
>
> when run, prints:
>
> <type 'list'> <class '__main__.MyList'>
> False
> True
>
> The docs say:
>
> [http://docs.python.org/library/stdtypes.html]
> Objects of different types, except different numeric types and different
> string types, never compare equal
>
> [http://docs.python.org/release/2.7/reference/expressions.html#notin]
> objects of different types (emphasis)always compare unequal
>
>
That definitely makes it unclear.  A little further down it says that you
can customize comparison with the __cmp__ special method.  You can also
override implement other specific comparison special methods, like __eq__ in
your classes.  So I can definitely see what you mean.

In the case of list, a list object has a __eq__ method that it uses for
determining equality, rather than using the __eq__ method of the base object
type (which behaves as described in your citation).  Many of the builtin
types have custom special methods for a variety of operators, including
comparison.

Looking over the documentation, it seems like it could be touched up to
alleviate any confusion.  Perhaps rewording to make it clear that the
described behavior is the default for objects, rather than always the case.

-eric


> In the test code above, l1 an l2 are different types, at least in the
> sense that type() returns something different for each of them.  What's
> the intended behavior here?  Either the code is wrong or the docs are
> wrong.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110512/1d85f9e1/attachment-0001.html>


More information about the Python-list mailing list