Does Python need an 'xor' operator?

Andrew Dalke dalke at dalkescientific.com
Mon Apr 15 15:16:13 EDT 2002


logistix:
>It gets a little trickier though.  Here's the real reason for short-circuit
>evaulation:
>
>>>> a = 1
>>>> a or c
>1
>>>> c or a
>Traceback (most recent call last):
>  File "<interactive input>", line 1, in ?
>NameError: name 'c' is not defined
>>>>

Ken Peek:
>An undefined variable is a programming disaster waiting to
>happen, and so should ALWAYS throw an exception if you try
>to access it before it is defined.

Perhaps logistix used a bad example.  I think the point he was
making is that 'and' and 'or' does short circuit logic, so the
full expression is not evaluated every time.  This is useful,
as for expressions like

  value = kwargs.get("-filename") or ask_user_for_filename()

where if the filename isn't specified, say, on the command line
then there's an interactive prompt to get it from the user.

This is useful since the other approach is

value = kwargs.get("-filename")
if not value:
  value = ask_user_for_filename()

which is longer so harder to read.  This is even more useful for
chains where

  value = f() or g() or h()

which I've used often for getting values which can be from multiple
sources (as with the chain command-line, environment variable, config
file, default setting).  The 'if' for this is 5 lines long.

Because of the short circuiting, 'and' and 'or' must done as operators
and not as function calls.  On the other hand, xor must evaluate both
terms to do the computation, so there is less need for xor to be
a new operator.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list