Python's and and Pythons or

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Oct 9 20:36:20 EDT 2013


On Wed, 09 Oct 2013 16:54:03 -0700, Peter Cacioppi wrote:

> I really like the logic that Pythons "or" is not only short-circuit but
> non-typed.
> 
> So I can say
> 
> y = override or default
> 
> and y won't necc be True or False. If override boolean evaluates to True
> (which, for most classes, means not None) than y will be equal to
> override. Otherwise it will be equal to default.
> 
> I have two questions
> --> Is there a handy name for this type of conditional (something as
> catchy as "short circuit or")

I don't know about catchy. I think of it as just a special case of duck-
typing -- all objects can be duck-typed as if they were bools.

Some terms that are often used:

"boolean context"
"truth context"
"truthiness"

The values themselves are described as "truthy" and "falsey", or "true-
like" and "false-like", or even just "true and false" (as opposed to True 
and False). Other languages (Ruby, PHP, Javascript, etc.) also have 
truthy and falsey values, but in my opinion none of them have got it 
right. Python has a unifying model of truthiness: objects which represent 
"something" ought to be truthy, those which represent "nothing" ought to 
be falsey:


# Nothing
empty strings '', u''
empty list, tuple, dict [] () {}
empty set, frozenset
None
zero 0, 0.0, 0j, Decimal("0.0"), Fraction(0)
any empty collection or mapping


# Something
all other strings
all non-empty lists, tuples, dicts
all non-empty sets, frozensets
object()
all non-zero numbers
any non-empty collection or mapping
anything else (by default)


while other languages appear to just have a grab-bag of whatever 
arbitrary values the language designer thought ought to be truthy/falsey.



> and
> 
> --> Is there a common idiom for taking advantage of the similar behavior
> of "and". The "override or default" just makes me grin every time I use
> it.


Not that I can think of.



-- 
Steven



More information about the Python-list mailing list