list equal to subclass of list?

Algis Kabaila akabaila at pcug.org.au
Thu May 12 09:41:54 EDT 2011


On Thursday 12 May 2011 22:23:04 Roy Smith 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.htm
> l#notin] objects of different types (emphasis)always compare
> unequal
> 
> 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.

Subclassing of lists can be tricky, as you have indicated. Here 
is another simple example:

Using Python 3.2,

>>> class Array(list):
	def __init__(self):
	    print(type(self))
	    temp = [[0,0], [0,0]]
	    print('temp =', temp)
	    self = temp[:]
	    print(type(self), type(temp))
	    print('self =', self)    
>>> a = Array()
<class '__main__.Array'>
temp = [[0, 0], [0, 0]]
<class 'list'> <class 'list'>
self = [[0, 0], [0, 0]]

So copying *values* of a list to a subclass of list ( tem[:]) 
makes converts the subclass back to its parent... 

The equality of list is rather an ambiguous concept.  For 
instance,  a euclidian vector is usually represented by a list 
of 3 vector components.  So if two vectors are of equal length 
and point in opposite directions, are they equal to each other?

The answer is clearly no.  

The other difficulty is that a list is creted by [], viz. lst = 
[].  So an array has to use the square brackets with great care 
not to be converted back to a list.  

Thanks for your nice example and pointers to docs.
OldAl.
-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110512/b703dd49/attachment-0001.html>


More information about the Python-list mailing list