Reputation: 811
let's assume following C code:
// events.h
enum Events {eOne, eTwo, eThree};
enum Events getEvent(void);
...
//ctrl.c
#include "events.h"
void ctrl(void)
{
switch(getEvent())
{
case eOne:
// ...
break;
case eTwo:
// ...
break;
case eThree:
// ...
break;
default:
;
}
}
What is pythonic way to implement this? The simple way for me, is to use strings instead of enums, but how can I be sure that all strings are typed correctly (i.e. are the same in all files)?
Upvotes: 1
Views: 2162
Reputation: 208565
The following Python code is similar to how your C code interacts. To use variables from another module you need to first import that module.
// events.py
class Events:
eOne, eTwo, eThree = range(3)
def getEvent():
# add code for getEvent here (might have been in events.c for C code)
return some_event
...
// ctrl.py
from events import Events, getEvent
def ctrl():
event = getEvent()
if event == Events.eOne:
# ...
elif event == Events.eTwo:
# ...
elif event == Events.eThree:
# ...
else:
# default
Upvotes: 2
Reputation: 16037
class Animal:
DOG=1
CAT=2
x = Animal.DOG
source: How can I represent an 'Enum' in Python?
Upvotes: 2
Reputation: 351586
Make the strings constants and then you can reference them by name so you don't have magic strings hanging around in the source code. You could define these constants in a common module or class.
Upvotes: 0