Question

Python has the usual bitwise operators, like ~, &, |, etc. and in-place operators like +=, &=, etc. to simplify expressions like:

a = a & 34234
a = a + 577

To:

a &= 34234
a += 577

Despite the complement operator ~ being an unary function, and not following the same structure because it isn't used with two values (like a and 34234), can expressions like these be simplified with another type of operator?

a = ~a # not bad at all

# Still easy to code but seems redundant
self.container.longVariableName.longName = ~self.container.longVariableName.longName
Was it helpful?

Solution

It's excruciatingly obscure, but:

self.container.longVariableName.longName ^= -1

does the job, so long as the values you're dealing with are integers. "Are integers" is required so that there's an exploitable mathematical relation between the ~ and ^ operators.

Why it works:

  1. Bitwise complement is the same as xor'ing with an infinite string of 1 bits.
  2. Python maintains the illusion that integers use an infinite-width 2's-complement representation, so that -1 "is" an infinite string of 1 bits.

OTHER TIPS

If you are only concerned about doing this for attributes of object instances, you could write a method like:

def c(obj, atr):
    setattr(obj,atr,~getattr(obj,atr))

and then use it like:

c(self.container.longVariableName, 'longName')

I think that @TimPeters answer is much better, but thought I'd provide this in case it is useful to anyone in the future who needs to do this with non-integers are is happy to only work with instant attributes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top