A better way for "except" and "return"?

Andrew Dalke dalke at dalkescientific.com
Sat Jan 12 16:05:01 EST 2002


Russell E. Owen wrote
>Most of the time you will want to test for equality ("=="). I'm not sure
>I've ever used "is" in code (except accidentally as an invalid
>substitute for "==" when I started out). (There are times when "is" will
>have the effect of testing for equality, but it's dangerous since you
>are not saying what you mean.)

Mostly I use 'is' for two cases:

  1.) to identify the None object

def function(x = None):
    if x is None:
        do_this()
    else:
        do_that(x)

If I used "x == None" then there's the possibility that, for other reasons,
the parameter passed in to the function implements __cmp__ or __eq__ to
let it be equal to None.  That would be subtle and unexpected.

BTW, there are other solutions to this problem, like

def function(*args, **kwargs):
    ... check to see that only one terms is defined ...

 -or-

class _NoArgGiven:
  pass
def function(x = _NoArgGiven):
  if x is _NoArgGiven:
      do_this()
  ...

  2.) For performance, 'is' is faster then '=='

The best example is when I was working on a graph search problem (really,
a chemical molecule represented as a graph).  By construction,
  atom1 == atom2 implies atom1 is atom2
  bond1 == bond2 implies bond1 is bond2

(This doesn't have to be true if the atoms and bonds are created by
proxy objects.  Hence the additional requirements by the algorithm.)

By putting on these restraints, my code could make equivalence with 'is' and
so not have to deal with the __cmp__ overhead.

                                     Andrew
                                     dalke at dalkescientific.com






More information about the Python-list mailing list