Mailing List Archive

Regarding the magical "or" operator
I was wondering how often most python programmers make use of that
remarkably nifty property of the logical operators, in which they
produce not merely 0 or 1, but the value is last looked at when it
decided whether the expression was true or false.

For example:

print [] or "Some"
Some

print "Peter" and "Paul"
Paul

print (20 - 4*5) or None
None

My question is this: have you ever had an urge for it (or a variant)
to care about the difference between None and any other false value?
I am certainly *not* asking for such a thing. I'd just like to know
whether anyone ever cared. For example, given these three functions:

def f():
return []

def g():
return None

def h():
return ["Some"]

Consider these prints:

print f() or h()
['Some']

print g() or h()
['Some']

The idea would be a version of "or" that would return the first non-None
value. For example, supposing this were called "nor" (silly name,
but this is *not* a proposal):

print f() nor h()
[]

print g() nor h()
['Some']

The argument is that this would be used not with prints, but with
assignments, as in

a = f() nor g()

The reason I ask is not because I actually want such a thing. Gosh, no.
I'm rather uncomfortable with the idea. I'm just trying to gather some
understanding and perspective for use with the folks who *would* like
such an oddity. :-)

--tom
--
Mister Catbert, the company is trying to force me to use a different kind
of computer. You're the human resources directory. what are you doing
to sop this religious persecution?! What every happened to "Diversity"??
The longer you verk here, diverse it gets. next. --Scott Adams, "Dilbert"
Regarding the magical "or" operator [ In reply to ]
Hi Tom!

On 14 Aug 1999, Tom Christiansen wrote:

> I was wondering how often most python programmers make use of that
> remarkably nifty property of the logical operators, in which they
> produce not merely 0 or 1, but the value is last looked at when it
> decided whether the expression was true or false.

I'm not sure about most python programmers. It's a feature of the
language that I always teach in my courses, and I tend to get blank looks
at first. I find that once I motivate the or behavior with an example
like:

title = windowname or 'Untitled'

a few folks think it's neat (and I guess from that that they plan on using
it, or at least trying it). I use it periodically, although not very
often.

Not that you asked, but I find the 'and' behavior much harder to motivate
and grok, and I avoid it personally.

> My question is this: have you ever had an urge for it (or a variant)
> to care about the difference between None and any other false value?
[...]
> The idea would be a version of "or" that would return the first non-None
> value. For example, supposing this were called "nor" (silly name,
> but this is *not* a proposal):
>
> print f() nor h()
> []
>
> print g() nor h()
> ['Some']
>
> The argument is that this would be used not with prints, but with
> assignments, as in
>
> a = f() nor g()
>
> The reason I ask is not because I actually want such a thing. Gosh, no.
> I'm rather uncomfortable with the idea. I'm just trying to gather some
> understanding and perspective for use with the folks who *would* like
> such an oddity. :-)

FWIW, it doesn't grab me. I'd read 'a nor b' as 'not (a or b)', and I
know too much about truth and falsehood in Python to expect None to be
treated differently.

(It's a nice word, though. One that, alas, Dr. Seuss didn't use when he
should have in One Fish, Two Fish, Red Fish, Blue Fish.)

--david ascher
Regarding the magical "or" operator [ In reply to ]
[posted & mailed]

[Tom Christiansen]
> I was wondering how often most python programmers make use of that
> remarkably nifty property of the logical operators, in which they
> produce not merely 0 or 1, but the value is last looked at when it
> decided whether the expression was true or false.

Hard to say. It shows up dozens of times in the std libraries, but like
other features that aren't exactly like C's, I'd guess "most programmers"
don't think to use it ("else" clauses on loops are similar this way).

The most common idiom is

value_to_use = some_value or some_default_value

A cute one is in the Wichmann-Hill random # generator, where a seed int
cannot be allowed to become 0:

x = (x + a) % 256 or 1

> ...
> My question is this: have you ever had an urge for it (or a variant)
> to care about the difference between None and any other false value?

Whaddya think this is, Perl <wink>?

> I am certainly *not* asking for such a thing. I'd just like to know
> whether anyone ever cared.

Not that I recall. The notion that "one distinguished false value is more
false than the others" wouldn't fly well here. None doesn't come with
enough semantics (either enforced or conventional) to support making subtle
distinctions -- None evaluates false, and has an easy-to-remember name, but
there's nothing else special about it in theory or practice.

It may be different in Perl, where e.g. I imagine that an operator returning
the first non-undef value could be handy. It would be handy in Python too
*if* e.g. unbound names were instead bound to None by default (instead of
raising exceptions upon reference).

In Python-land folks are more likely to clamor for an equivalent to Perl/C

a = b() ? c() : d()

The simplest faithful Python one-liner

# trickiness needed in case c() evaluates false;
# [c()] is still true in that case
a = (b() and [c()] or [d()])[0]

makes

if b():
a = c()
else:
a = d()

look downright appealing <wink>.

none-is-its-own-reward-ly y'rs - tim
Regarding the magical "or" operator [ In reply to ]
Tom Christiansen wrote:
[...]
> My question is this: have you ever had an urge for it (or a variant)
> to care about the difference between None and any other false value?
> I am certainly *not* asking for such a thing. I'd just like to know
> whether anyone ever cared.
[...]

Yes, this has happened to me a few times. The usual setup is a
function that normally either returns a list or a numerical value,
but can fail in some circumstances, and where, obviously, [] or 0
are valid return values. In most cases, another look at the problem
will reveal a missed opportunity to throw an exception for the
failed case.

There may be situations where an exception would at least *look*
like too much overhead. But with the current semantics, the extra
check for None is not really simpler or faster to type.
With your unproposed "nor" operator, the situation would change
a little. But then, even this would only apply to the special
case where the resulting value is used in an assignment.
As soon as other decisions depend on this result, the standard
exception handling seems to result in the most readable code,
especially in combination with the "else" and "finally" clauses
after "try" and "except".

And yes, I recently have started to use "or" and "and" as
assignment value selectors, as well as the abovementioned "else"
in exception handling and in looping constructs. It doesn't happen
very often, but can simplify the code a lot in some situations.
Given my lisp background, it's actually surprising that I lived
without noticing those possibilities for my first few years
of Python exposure...


Have fun!

-schorsch

--
Georg Mischler -- simulation developper -- schorsch at schorsch.com
+schorsch.com+ -- lighting design tools -- http://www.schorsch.com/


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
Regarding the magical "or" operator [ In reply to ]
>My question is this: have you ever had an urge for it (or a variant)
>to care about the difference between None and any other false value?


I get along fine without it by testing "myVar is None" to distinguish it
from other false values. However, (trying to see your point) I guess if I
were thinking about None like an IEEE NaN, or like a database NULL, it might
bother me that "not None" is 1.
Regarding the magical "or" operator [ In reply to ]
<color><param>0100,0100,0100</param>On 14 Aug 99, at 23:09, Tim Peters wrote:


</color>> [posted & mailed]

>

> [Tom Christiansen]

> > My question is this: have you ever had an urge for it (or a
variant) to

> > care about the difference between None and any other false value?

>

> Whaddya think this is, Perl <<wink>?


<color><param>0000,0000,0000</param>Or maybe Pike.


Here's an example of what we DON'T want, taken from the Pike reference
manual:


NAME

zero_type - return the type of zero


SYNTAX

int zero_type(mixed a);


DESCRIPTION


There are many types of zeros out there, or at least there are two. One
is returned by normal functions, and one returned by mapping lookups
and find_call_out() when what you looked for wasn't there. The only way
to separate these two kinds of zeros is zero_type. When doing a
find_call_out or mapping lookup, zero_type on this value will return 1
if there was no such thing present in the mapping, or no such call_out
could be found. If the argument to zero_type is a destructed object or
a function in a destructed object, 2 will be returned. Otherwise
zero_type will return zero. If the argument is not an int,

zero will be returned.
Regarding the magical "or" operator [ In reply to ]
Tom Christiansen wrote:
>
> My question is this: have you ever had an urge for it (or a variant)
> to care about the difference between None and any other false value?

Personally I think there should be a separate Boolean type,
and it should be an error to test the truth of any other type.

Alternatively, the Scheme convention could be used, where
the one and only false value is the boolean one, and everything
else is true.

There should be an "else" operator for doing what the "or"
trick is currently used for. The expression

a else b

should return a unless it is None (and only None), in which
case it should evaluate and return b.

(I don't like the idea of calling it "nor", because that
word already has a meaning in computing which is quite
different.)

Greg
Regarding the magical "or" operator [ In reply to ]
>>>>> "GE" == Greg Ewing <greg.ewing@compaq.com> writes:

GE> Personally I think there should be a separate Boolean type,
GE> and it should be an error to test the truth of any other type.

Last time the idea of a boolean type was brought up, I think we zeroed
<wink> in on the attached Python prototype. I'm not sure I like the
second half of your proposal; it works okay I s'pose in Java, but
doesn't seem right in Python.

-Barry

-------------------- snip snip --------------------
class Bool:
def __init__(self, flag=0):
self.__flag = not not flag

def __str__(self):
return self.__flag and 'true' or 'false'

def __repr__(self):
return self.__str__()

def __nonzero__(self):
return self.__flag == 1

def __cmp__(self, other):
if (self.__flag and other) or (not self.__flag and not other):
return 0
else:
return 1

def __rcmp__(self, other):
return -self.__cmp__(other)

true = Bool(1)
false = Bool()