Python's and and Pythons or

P

Peter Cacioppi

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")

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.

Thanks
 
S

Steven D'Aprano

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.
 
C

Chris Angelico

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

Python's model makes a lot of sense. The only other system that I've
seen that makes as much sense is Pike's, which can be summarized as:

Falsey:
0 (the integer; does the job of None in many contexts)

Truthy:
Everything else.

Python lets you distinguish easily between an empty list and a list
with something in it; Pike lets you distinguish between a list and the
absence of a list.

The use of 'and' and 'or' in returning their arguments is an extremely
useful one, but I'm not sure it has a name. Pike and Lua have the same
behaviour; neither offers a good term for it. Recommendation: Invent a
term if you can't find one, and start using it. :)

ChrisA
 
P

Peter Cacioppi

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")



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.



Thanks

ok, since someone asked, I suggest we call the "return it's arguments" behavior "echo-argument".

That is to say, the reason we can write

y = override or default

is because Python implements echo-argument or. That is to say, "or" doesn't necc return True or False, "or" returns the first "truthy" argument it encounters.

"and" behaves similarly, in that it returns the first "falsey" argument it encounters.

I'm trying to think of a good example usage of echo-argument and. Maybe something like

possible = foo and foo.allowsit()
if (possible is None) :
print "foo not provided"
if (possible is False) :
print "foo doesn't allow it"

A bit awkward, echo-argument or is more naturally useful to me then echo-argument and.
 
C

Chris Angelico

I'm trying to think of a good example usage of echo-argument and. Maybe something like

possible = foo and foo.allowsit()
if (possible is None) :
print "foo not provided"
if (possible is False) :
print "foo doesn't allow it"

A bit awkward, echo-argument or is more naturally useful to me then echo-argument and.

first_element = some_list[0] # Oops, may crash

try:
first_element = some_list[0]
except IndexError:
firstelement = None # A bit verbose

first_element = some_list and some_list[0]

# or if you want a zero instead of an empty list:
first_element = len(some_list) and some_list[0]


Also, consider the case where you have a function, or None:

result = func(*args,**kwargs) # NoneType is not callable

result = func and func(*args,**kwargs)

ChrisA
 
E

Ethan Furman

I'm trying to think of a good example usage of echo-argument and. Maybe something like

possible = foo and foo.allowsit()
if (possible is None) :
print "foo not provided"
if (possible is False) :
print "foo doesn't allow it"

A bit awkward, echo-argument or is more naturally useful to me then echo-argument and.

It's used as a guard:

if some_list and some_list[0] == something_or_other:
do some_work()

Without the 'some_list and' portion when some_list was either empty or, say, None, the some_list[0] would fail with an
error (IndexError, TypeError, etc.).
 
P

Peter Cacioppi

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")



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.



Thanks

So you can wrap it all up in one big example

y = (overrideprovider and overrideprovdider() ) or default

echo-argument and/or is a beautiful thing
 
T

Terry Reedy

I'm trying to think of a good example usage of echo-argument and. Maybe something like
A bit awkward, echo-argument or is more naturally useful to me then echo-argument and.

first_element = some_list[0] # Oops, may crash

some_list[0:1] always works, and sometimes is usable, but you still
cannot index the slice.
try:
first_element = some_list[0]
except IndexError:
firstelement = None # A bit verbose

first_element = some_list and some_list[0]

# or if you want a zero instead of an empty list:
first_element = len(some_list) and some_list[0]


Also, consider the case where you have a function, or None:

result = func(*args,**kwargs) # NoneType is not callable

result = func and func(*args,**kwargs)

y = x and 1/x
One just has to remember that y==0 effectively means y==+-infinity ;-).
 
C

Chris Angelico

y = x and 1/x
One just has to remember that y==0 effectively means y==+-infinity ;-).

Good example. Extremely appropriate to situations where you're showing
a set of figures and their average:

Foo 1
Bar 3
Quux 7
Asdf 9
===== 5

Let the average show as zero if there are none, it won't hurt:

print("=====",count and total/count)

ChrisA
 
E

Ethan Furman

I'm trying to think of a good example usage of echo-argument and. Maybe something like
A bit awkward, echo-argument or is more naturally useful to me then echo-argument and.

first_element = some_list[0] # Oops, may crash

some_list[0:1] always works, and sometimes is usable, but you still cannot index the slice.

Not if some_list is None, False, or another non-indexable type.
 
T

Terry Reedy

On 10/10/2013 12:43 AM, Terry Reedy wrote:
first_element = some_list[0] # Oops, may crash
some_list[0:1] always works, and sometimes is usable, but you still
cannot index the slice.
Not if some_list is None, False, or another non-indexable type.

Did you really not understand that some_list is intended to be a list?
Just like my_string, for instance, would be a string? Chris's statement
further specifies some_list as a list that is expected to not be empty,
but might be -- so one has to guard against the possibility.

The trick of slicing instead of indexing in this context is not obvious
to everyone learning Python. Most other languages only have indexing. I
learned the trick years ago when someone posted it on this list.
 
E

Ethan Furman

On 10/10/2013 12:43 AM, Terry Reedy wrote:
On 10/10/2013 2:45 AM, Chris Angelico wrote:
first_element = some_list[0] # Oops, may crash
some_list[0:1] always works, and sometimes is usable, but you still
cannot index the slice.
Not if some_list is None, False, or another non-indexable type.

Did you really not understand that some_list is intended to be a list? Just like my_string, for instance, would be a
string? Chris's statement further specifies some_list as a list that is expected to not be empty, but might be -- so one
has to guard against the possibility.

I understood it just fine. I'm also aware that at some point, in some program, it will be None (and it won't be a bug ;).

The trick of slicing instead of indexing in this context is not obvious to everyone learning Python. Most other
languages only have indexing. I learned the trick years ago when someone posted it on this list.

It's a good trick, I use it myself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,815
Latest member
treekmostly22

Latest Threads

Top