[Tutor] 'or' in assignment (not if statement)?

ALAN GAULD alan.gauld at btinternet.com
Fri Dec 10 09:46:25 CET 2010

> Doesn't  short-circuit evaluation refer specifically to the behavior
> where arguments  are only evaluated if they need to be? It's a very
> useful feature, but not  technically required for the "val = val or 1"
> behavior to work.

Its essential.
If Python always evaluated all parts of a boolean expression 
the return value would always be the last item. It's the fact that 
Python knows that if val is true then it doesn't need to evaluate 
the second term that causes it to return val rather than 1.

> Also,  returning on of its operands rather than a boolean is hardly a
> quirk, since  basically all dynamic languages do it ever since perl
> made "val = val or 1"  an idiom (at least, I think it was perl).

Its a quirk in that it is not the intuitively expected behaviour.
It's a boolean expression you would reasonably expect a 
true boolean result.

I think you are right that Perl was the first popular language to 
do this, but Perl is a relatively recent arrival (abouit the same 
time as Python - 1988-90?) and it has become a feature of 
many recent dynamic languages. But most static languages 
still return true boolean values.

Alan G.

More information about the Tutor mailing list