1

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)?

ivand58
  • 773
  • 6
  • 19
  • Are you asking for the pythonic way to implement `enum`s, the pythonic way to implement `switch` statements, the pythonic way to communicate between modules, or something else? Could you supply more code? There are different solutions depending on what you are doing. – Nate Dec 07 '11 at 19:58
  • @ivand58: What is the use case that you think of regarding communication between modules? – pyfunc Dec 07 '11 at 19:58
  • Can you provide a user scenario? From the look of it, I think all you need is to install [`carrot`](http://ask.github.com/carrot/introduction.html)... ;) but I might be missing something! – mac Dec 07 '11 at 19:59

3 Answers3

2
class Animal:
    DOG=1
    CAT=2

x = Animal.DOG

source: How can I represent an 'Enum' in Python?

Community
  • 1
  • 1
bpgergo
  • 15,669
  • 5
  • 44
  • 68
2

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
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

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.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635