Pipe in the "return" statement

Ethan Furman ethan at stoneleaf.us
Mon Jul 25 22:07:08 CEST 2011


Billy Mays wrote:
> On 07/25/2011 10:16 AM, Archard Lias wrote:
>> On Jul 25, 2:03 pm, Ian Collins<ian-n... at hotmail.com>  wrote:
>>> On 07/26/11 12:00 AM, Archard Lias wrote:
>>>> Still I dont get how I am supposed to understand the pipe and its task/
>>>> idea/influece on control flow, of:
>>>> return<statement>    |<statement>
>>>> ??
>>>
>>> It's simply a bitwise OR.
>>
>> Yes, but how does it get determined, which one actually gets returned?
> 
> The return statement returns a single value from a function context. The 
> pipe operator takes 2 values and bitwise ORs* them together.  That 
> result is then returned to the caller.

Just for completeness, if the actual line had been

return <statement1> or <statement2>

then Python would compute <statement1>, and if its boolean value was 
True would return the computation of <statement1>, otherwise it would 
compute <statement2> and return that.  When 'or' is used, the first 
truthy* item is return, or the last falsey* item if none evaluate to True.

--> None or 2 or 0
2
--> None or 2 or 3
2
--> None or [] or 0
0

With 'and', the first falsey item is returned, unless all the items are 
   truthy in which case the last item is returned:

--> 2 and 3
3
--> 2 and 0 and 9
0

Hope this helps.

~Ethan~

* 'truthy' = bool(some expression or object) == True
* 'falsey' = bool(some expression or object) == False



More information about the Python-list mailing list