Result of ``a is b''

David MacQuigg dmq at gain.com
Thu Mar 18 20:50:17 CET 2004



>At some point, David MacQuigg <dmq at gain.com> wrote:
>> I can't see where the 'is' test would *ever* be needed for the above
>> comparisons.
>
On Thu, 18 Mar 2004 01:17:53 -0500, cookedm+news at physics.mcmaster.ca
(David M. Cooke) wrote:
>I do a lot of stuff with arrays in Numeric, which override __eq__ to
>elementwise comparision:
>
>Python 2.3.3 (#2, Feb 24 2004, 09:29:20) 
>[GCC 3.3.3 (Debian)] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
>>>> import Numeric
>>>> x = Numeric.array([0,1,2,3])
>>>> x == None
>array([0,0,0,0])
>>>> bool(x == None)
>False
>>>> x is None
>False
>>>> x == False
>array([1,0,0,0])
>>>> bool(x == False)
>True
>>>> x is False
>False
>>>> bool(x == True)
>True
>>>> bool(x == True and x == False)
>True
>
>[Ok, so bool(x == None) returns False, which is good, but imagine the
>overhead if x was an array of several million elements. x == None
>would allocate a new array of the same size.]

For the rare case where storage of None elements is an issue, could
you define your own 'none' object, and simply point all references to
it.  That would allow you to use 'is', avoiding the overhead of '==',
and not mess with the normal definition of '=='.  Most importantly, it
would allow you to use 'is' with confidence that a Python
implementation change, or a move to a new platform, won't trash your
program.

>>> class none:
	def __repr__(self):
		return 'none'
	... whatever other attributes you need for 'none'

>>> n0 = none()
>>> n1 = n2 = n0
>>> n1 == n2
True
>>> n1 is n2
True
>>> n1
none
>>> 

-- Dave




More information about the Python-list mailing list