2

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
2
  • 2
    Use shorter variable names. If using it twice is too cumbersome, I find it hard to imagine that using it once would be any better. Commented Jan 4, 2014 at 3:19
  • @SlaterTyranus this is a bit of a made-up issue, I know. The real question to me is about a possible ~=-like operation. And sometimes shorter variable names aren't favourable over ones that are easily understood, depending on the application. Commented Jan 4, 2014 at 3:32

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. I suppose a bit more knowledge on bitwise operations would have let me find this myself. Then it's a tradeoff since I'd probably need to write a small comment beside it to clarify for others reading the code. Thanks.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.