Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does if x: mean in Python

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading