Python's and and Pythons or

Peter Cacioppi peter.cacioppi at gmail.com
Thu Oct 10 02:12:49 EDT 2013


On Wednesday, October 9, 2013 4:54:03 PM UTC-7, 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")
> 
> 
> 
> 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.






More information about the Python-list mailing list