Search code examples
pythondata-modelingmodelsmodeling

How do you model a state with three values?


I have something which can be in three states

(say) Open, Closed, Running

I will try to model it via one of the two ways,

is_open = Boolean(default=False)
is_running = Boolean(default=False)

and Disallow the state (say) is_running=True, is_open = False in application code.

I can also try

state=Char(choices=("O", "C", "R"))

Is one of the ways better, and is there any better way to do this?

Edit: I am using Python (and Django).
Edit 2: After reading the answers below, I guess I am trying to simulate Enums in Python(Which doesnt have them) in a form which is suitable for persisting to DB


Solution

  • The simplest way to handle this in Python is to use string constants. We did exactly that when adding inspect.getgeneratorstate() to Python 3.2. The possible return values from that function are:

    GEN_CREATED = 'GEN_CREATED'
    GEN_RUNNING = 'GEN_RUNNING'
    GEN_SUSPENDED = 'GEN_SUSPENDED'
    GEN_CLOSED = 'GEN_CLOSED'
    

    Creating a simple class as a namespace for the constants is another common option (but the attributes of that class should still be strings rather than integers).

    In Python, there is minimal gain in using integers over strings for your constants. You lose a little in comparison speed (but not much, due to hash caching and other string comparison optimisations) and use slightly more memory (but not much, since references are the same size regardless of the type of the target), but vastly simplify debugging (since you don't need to translate integer codes to meaningful state names - you can just display the string values).