Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Operator |= meaning

Tags:

python

due to some versioning problems with python I am bound to use a custom function to compare HMACs (SHA512). To do so I have found this function:

def compare_digest(x, y):
    if not (isinstance(x, bytes) and isinstance(y, bytes)):
        logfile.debug("both inputs should be instances of bytes")
    if len(x) != len(y):
        return False
    result = 0
    for a, b in zip(x, y):
        result |= a ^ b
    return result == 0

I am using this in Django, hence I created a logger (logfile) that saves debug messages into a file for me.

The code breaks at this step:

result |= a ^ b

However, I have no idea what the |= operator stands for and what happens here. If someone could explain this I could try to rewrite this.

My python version is (unfortunately 2.7.4) with 2.7.7 I would not have the problem, as the function would have been ported correctly and made available.

like image 998
muffin2015 Avatar asked Apr 01 '15 19:04

muffin2015


1 Answers

| is the bitwise OR operator. |= is the bitwise OR equivalent of +=, -=, etc. Basically, a |= b is shorthand for a = a | b.

like image 199
a p Avatar answered Nov 02 '22 22:11

a p