5

Consider the C function int get_events(), which returns a bitmask of the following events:

#define EVENT_KEY_DOWN    1
#define EVENT_KEY_UP      2
#define EVENT_KEY_PRESS   4

It could return 5, for example, meaning both EVENT_KEY_DOWN and EVENT_KEY_PRESS were triggered.

I thought about the following ways to return the value from the function to Python code:

  • "as is", i.e. 5
  • a tuple of integers: (1, 4)
  • a tuple of strings: ('EVENT_KEY_DOWN', 'EVENT_KEY_PRESS')

(In all cases I could declare constants like mymodule.EVENT_KEY_DOWN and mymodule.EVENT_KEY_PRESS, as well.)

Is there any "recommended" way?

Rômulo Ceccon
  • 10,081
  • 5
  • 39
  • 47
  • In most languages, flags/bitmasks stored as non-integer types often result in more work. That said, since you can do `if 'EVENT_KEY_PRESS' in mask:` or similar, I don't see a downside to using tuples of constant strings in python .That said, I'd declare a variable `EVENT_KEY_PRESS` with some unique value so you can avoid Typos in the string – Basic Mar 03 '15 at 14:45
  • I would go for a set of strings `set(('EVENT_KEY_UP', 'EVENT_KEY_PRESS'))` – mkiever Mar 03 '15 at 14:48
  • The problem is change, if you can guarantee that your C/Python definitions will be properly updated and in sync during the lifetime of the project, and that you won't have different versions interacting with each other, then use bitmasks. Otherwise it might be a good idea to represent them with strings. – imreal Mar 03 '15 at 14:49
  • It's easy enough to handle bitmasks in Python, and if that's what the underlying GUI system is using why bother converting back and forth to some other representation? Eg, see http://www.pygtk.org/pygtk2reference/gdk-constants.html#gdk-event-mask-constants – PM 2Ring Mar 03 '15 at 14:51
  • I think exporting integer constants at the module level is the normal approach, at least for Python 2.x, haven't done much 3.x. See modules `socket`, `serial`, `gtk`, `os`, `pygame` and many others as reference modules that wrap `c` libraries. – Brian McFarland Mar 03 '15 at 15:28
  • As another example (showing exactly what you're asking about) PySDL `get_events` function returns module-level integer constants. – Brian McFarland Mar 03 '15 at 15:32

1 Answers1

0

Sparse is better than dense; readability counts. I'd choose the tuple of strings by that logic, but also take a look at patterns for how you'll use the API. If you're in a performance-critical code path, for example, you should consider just leaving it as a bitmask.

Matt Cooper
  • 927
  • 9
  • 16