Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does adding '=' do to bit operators in Python? (ie '<<=' instead of '<<')

What do the <<=and the |= operators mean Python? I guess they are bitwise operators. I know the operators | (bitwise or) and << (bit shifting), but I don't know them in combination with the =.

I found it in this piece code. Code below belongs to that code.

commandout = adcnum
commandout |= 0x18  # start bit + single-ended bit
commandout <<= 3    # we only need to send 5 bits here
for i in range(5):
    if (commandout & 0x80):
        GPIO.output(mosipin, True)
    else:
        GPIO.output(mosipin, False)
    commandout <<= 1
    GPIO.output(clockpin, True)
    GPIO.output(clockpin, False)
like image 470
OrangeTux Avatar asked Dec 27 '22 06:12

OrangeTux


1 Answers

Both are in-place assignments; they effectively give you name = name op right-hand-expression in the space of just name op= right-hand-expression.

So for your example, you could read that as:

commandout = commandout | 0x18
commandout = commandout << 3

That is oversimplifying it a little, because with dedicated hooks for these operations the left-hand-side object can choose to do something special; list += rhs is really list.extend(rhs) for example, not list = list + rhs. An in-place operator gives a mutable object the chance to apply the change to self instead of creating a new object.

For your example, however, where I presume commandout is an int, you have immutable values and the in-place operation has to return a new value.

like image 149
Martijn Pieters Avatar answered Jan 18 '23 23:01

Martijn Pieters