Regarding the magical "or" operator
tim_one at email.msn.com
Sun Aug 15 05:09:54 CEST 1999
[posted & mailed]
> 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()])
a = c()
a = d()
look downright appealing <wink>.
none-is-its-own-reward-ly y'rs - tim
More information about the Python-list