list equal to subclass of list?

Ethan Furman ethan at stoneleaf.us
Thu May 12 12:43:23 EDT 2011


Roy Smith wrote:
> 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

This part of the documentation is talking about built-in types, which 
your MyList is not.


> [http://docs.python.org/release/2.7/reference/expressions.html#notin]
> objects of different types *always* compare unequal

Should probably have the word 'built-in' precede 'types' here, since 
constructed objects can do whatever they have been told to do.

> 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.

--> MyList.__mro__
(<class '__main__.MyList'>, <type 'list'>, <type 'object'>)

MyList is a list -- just a more specific kind of list -- as can be seen 
from its mro; this is analogous to a square (2 sets of parallel lines 
joined at 90 degree angles, both sets being the same length) also being 
a rectangle (2 sets of parallel lines joined at 90 degree angles).

> What's the intended behavior here?  Either the code is wrong or the docs
 > are wrong.

The code is correct.

~Ethan~

PS
Yes, I know my square/rectangle definitions are incomplete, thanks.  ;)



More information about the Python-list mailing list