What does if x: mean in Python

Question:

I have the following code segment in python


if mask & selectors.EVENT_READ:  
    recv_data = sock.recv(1024)  
    if recv_data:
        data.outb += recv_data
    else:
        print(f"Closing connection to {data.addr}")

Would I read this as: ‘if mask and selectos.EVENT_READ are equivalent:’
And similarly: ‘if recv_data is equivalent to true:’

Help is greatly appreciated!

Asked By: user8901723980173

||

Answers:

All values have an inherent Boolean value. For the bytes value returned by sock.recv, the empty value b'' is false and all other values are true. This is a short, idiomatic way of writing

if recv_data != b'':
    ...

The & is a bitwise AND operator. The result of mask & selectors.EVENT_READ produces a value where a bit is 1 if both mask and selectors.EVENT_READ have a 1, and 0 otherwise. The result of that is an integer which may or may not be 0 (and for int values, 0 is false and all others are true).

Basically, mask & selectors.EVENT_READ is true if and only if any of the bits set in selectors.EVENT_READ are also set in mask.

Answered By: chepner

For the second assumptions, yes.

if var_name: is shorthand of saying if var_name evaluates to a truthy value.

Your first assumption is wrong though, a logical AND operation in python is actually and, not & – many languages do use an ampersand as a logical and, but this is usually a double ampersand, as in &&. A single ampersand is usually a bitwise AND, not a logical AND.

So in your code above, the first if statement is doing a bitwise (binary) AND on the selectors.READ_EVENT with a bitmask of mask. Basically its a way of asking if the values match, in a binary way. So if READ_EVENT is 010 and the mask is also 010, then the logic evaluates to true. Otherwise

Answered By: Noscere
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.