4

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.

Artemix
  • 8,257
  • 13
  • 47
  • 74
  • 1
    It may be more prevalent in certain specialized contexts, but for what it's worth, I have never seen Python code like this before (and by no means would I call it "common practice"). – StardustGogeta Jul 31 '19 at 14:07
  • 3
    Typically you would use an [`Enum`](https://docs.python.org/3/library/enum.html) for that. – a_guest Jul 31 '19 at 14:07
  • 1
    Unless memory is at a premium, I would just represent `state` as a set of values. `state.remove(CLOSED_STATE); if OPEN_STATE not in state: state.add(ANOTHER_STATE)`, etc. – chepner Jul 31 '19 at 14:08
  • Well, the `state` can already have some bits set, so using bitwise operations is needed. But overall, seems like you did really deep into some module or it might even be a code ported from another language? – h4z3 Jul 31 '19 at 14:09
  • @h4z3 no, it was meant to be like that for what I understand, not modules either, quite on the surface. – Artemix Jul 31 '19 at 14:31
  • I've seen it before, but it's not especially common. Usually for state machine manipulations I like to go for https://github.com/glyph/automat – Hatshepsut Aug 01 '19 at 04:23

1 Answers1

4

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”).

Davis Herring
  • 30,864
  • 3
  • 33
  • 65