Search code examples
pythonpython-3.xbooleanassignment-operator

Python: In-place "not'ing" of booleans


I sometimes have a dictionary of booleans like the following;

d = {'a': True, 'b': False, 'c': False}

which I use as a collection of switches which all have to be on (True) in order for some operation to happen. While iterating, these switches are then flipped, e.g.

for char in text:
    if char == '0':
        d['a'] = not d['a']  # State of 'a' is switched
    ...

The fact that 'a' has to be looked up twice in the above bothers me. Were I to represent the values of the switches by 1 and -1 I could do the switching like d['a'] *= -1, which only reference the d['a'] once.

Ideally Python would supply me with an in-place "not assignment" operator.


Solution

  • I found my operator! One can use the bitwise XOR assignment operator,

    d['a'] ^= True
    

    I haven't gotten my head around how the bitwise operators should be used with general Python types, but I guess they work as expected with respect to booleans.