Reputation: 8655
So, I've encountered this snippet in the code when digging a bit to check some logic behind states changes:
def doSomething(cls, state):
state &= ~CLOSED_STATE
if (state & OPEN_STATE) == 0:
state |= ANOTHER_STATE
return state
(where, CLOSED_STATE = 1, OPEN_STATE = 4, ANOTHER_STATE = 2)
So, from a fairly beginner Python dev, it took me a few mins to understand what each line was doing, let alone understand the whole logic.
I'm experience working with other languages, and if the idea is to just check some states logic and return something, I would never overcomplicate it using bitwise operations like that, but maybe its a common practice in Python, which I'm not knowledge of.
Thanks.
Upvotes: 4
Views: 87
Reputation: 40013
Storing boolean values as bits packed into integers is common in many languages, although it’s particularly prevalent in lower-level ones where operations like set intersection are otherwise cumbersome. It does have some conceptual advantages, like implicitly restricting the set of flags (although how many there are isn’t obvious); it also has practical advantages (beyond using the theoretical minimum amount of memory) like making serialization trivial.
In any event, it’s so common an idiom that the standard library now supports it; while it’s certainly unfamiliar to some programmers, I consider it a reasonable style choice in general (and wouldn’t term it “overcomplication”).
Upvotes: 4