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

Hugo Arts hugo.yoshi at gmail.com
Fri Dec 10 02:36:43 CET 2010


On Fri, Dec 10, 2010 at 2:07 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Alex Hall" <mehgcap at gmail.com> wrote
>>
>> val=val or 1
>
>> I am guessing that val is an int. If val==0, the 'or' kicks in and
>> val=1, else the or is not needed and val=val. Am I close?
>
> Yes this is a combination of what is known as short circuit evaluation of
> boolean expressions and a quirk of Python that returns the actual value of
> something that is being treated as a boolean.
>

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.

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

There is more to the innocent little or. See
http://docs.python.org/library/stdtypes.html#truth-value-testing
It works on any type, not just numbers, and operates by truth value
testing, which is more complicated than it might first seem.

Hugo


More information about the Tutor mailing list