Interesting behaviour of the assignment
Gareth McCaughan
Gareth.McCaughan at pobox.com
Fri Dec 29 18:31:51 EST 2000
Michael Esveldt wrote:
> This is a somewhat ignorant question, but if 'x == y' checks for 'x is
> y' first, why use 'is' at all? If you only get a tiny bit of speed out
> of using 'is' is it worth it to have this in the language at all? (Not
> that it would ever change, just curious.)
1. You get a bigger increase in speed from "is" when it returns
false.
2. You use "is" when you actually want to check object identity.
For instance, consider this nasty code:
class Foo:
...
def copy_thing_from(other_foo):
self.thing.destroy()
self.thing = other_foo.thing.copy()
It's nasty for several reasons. One of them is that if
you have a Foo -- call it "foo", say -- and do foo.copy_thing_from(foo),
then you'll lose. So you need to check that the thing you're
destroying isn't the same thing you're about to copy.
class Foo:
...
def copy_thing_from(other_foo):
if self.thing is not other_foo.thing:
self.thing.destroy()
self.thing = other_foo.thing.copy()
You might still want to do the destroy-and-copy if the two
"thing"s were == but not identical.
An example of somewhere where you really might want to do this
sort of thing: suppose you're working with very large numbers
(for cryptography or something). You might have a "Bignum" class
for them, and for reasons of efficiency you might want to make
some arithmetic operations able to happen in place. But it might
be very painful to make a.add_to(a) work completely in-place, so
you'd need to check for the possibility that that was happening.
3. Another use for object identity: the ability to make unique
objects. A random example:
class Foo:
def __init__(self):
self._wibble = []
def do_something(self, optional=self._wibble):
if optional is self._wibble:
return "optional not given"
else:
return "optional %s" % optional
Unless the user deliberately screws around, this enables you
to tell reliably whether an optional argument was given. If
you use None (for instance) as the default, this isn't so.
--
Gareth McCaughan Gareth.McCaughan at pobox.com
sig under construc
More information about the Python-list
mailing list