2

I was reading the following article:

http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading

I was not sure what the following function was returning:

def eof(self):
    '''Check whether there is no more content to expect.'''
    return not self.is_alive() and self._queue.empty()

Looked at question below:

python and / or operators return value

x and y, if x is false, then x, else y 

What is x in this case? Is it self.is_alive() or not self.is_alive()

Community
  • 1
  • 1
user3809938
  • 1,114
  • 3
  • 16
  • 35

3 Answers3

4

For expressions without parentheses, Python uses a concept called operator precedence to determine what to evaluate first.

The not operator has a higher precedence than the and operator, so your expression is parsed as:

    (not self.is_alive())
and 
    self._queue.empty()

and self.is_alive() is called first. If that returns True, the not expression produces False, and the self._queue.empty() expression is not even run. The False result from not self.is_alive() is returned. After all, there is no way the and expression can become true with the left-hand-side of the expression already determined to be false.

If self.is_alive() returns False on the other hand, not False becomes True, and the result of self._queue.empty() is returned from the whole expression.

So, provided self._queue.empty() your function returns a boolean, the eof() method will return False if the object is still alive or the queue is not empty. It'll return True only if the object is no longer alive and the queue is empty.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
 return not self.is_alive() and self._queue.empty()

I think return not is not the phrase, rather not self.is_alive() is the phrase which will give you True when self.is_alive() is False and vice verca

Consider this:

return not self.is_alive() and self._queue.empty()

If you know about short-circuiting of conditional statement, you will know that,

if self.is_alive() is true, false is evaluated for this portion and it won't go to self._queue.empty(). It will return immediately.

But if self.is_alive() is false, true is evaluated from first portion, then it will check the second portion.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
1

it is not self.isalive()

the other alternative would be not(self.isalive() and self.queue.empty())

since not is higher precedence than and it is before the and

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179