1

That's a really dumb question for sure (and perhaps a bit opinion-based), but how do I create an enum-like object that stores things like error codes, which are constant and to be accessed later in code?

It occurs to me that there are four choices:

1) one status code - one variable

STATUS_NEW = 0
STATUS_PENDING = 1
STATUS_DONE = 2
STATUS_ERROR = -1

if some_object.status == STATUS_NEW:
    print 'this object is pretty fresh!'

This doesn't look good to me.

2) a dictionary containing all status codes with its name as the key:

STATUS = {'new': 0, 'pending': 1, 'done': 2, 'error': -1}

if some_object.status == STATUS['new']:
    print 'you got the idea.'

This looks uglier, but still, one object is better than several ones.

3) a named tuple looks even better, but it's it looks much worse to me at its initialization:

STATUS = namedtuple('Status', ['error', 'new', 'pending', 'done'])
STATUS = STATUS(error=-1, new=0, pending=1, done=2)

if some_object.status == STATUS.new:
    print 'looks prettier than using dict!'

4) Using a class:

class Status:
    NEW = 0
    PENDING = 1
    DONE = 2
    ERROR = -1

if some_object.status == Status.NEW:
    pass

Am I missing something? What is more encouradged?

Thanks in advance!

Igor Hatarist
  • 4,287
  • 2
  • 27
  • 40
  • I'd go with option 2, but that's coming from a C++ background, and that feels the most like an enum, which is how I would probably approach this. – Cory Kramer Oct 14 '14 at 12:33
  • 2
    Several ways to implement enums in [this answer](http://stackoverflow.com/a/1695250/202775) – tuomur Oct 14 '14 at 12:38

2 Answers2

13

Enums in python are designed exactly for this.

from enum import Enum

class STATUS(Enum):
    NEW = 0
    PENDING = 1
    DONE = 2
    ERROR = -1

Enums are available starting from 3.4. If you aren't so lucky pypi has a backport available.

simonzack
  • 16,188
  • 11
  • 62
  • 100
1

For python < 3.4 I personally prefer 4th one, but...

if some_object.status == Status.NEW:
    pass

Don't do that. You may want to return error code for external tools, but in all-Python environment you should use exceptions. Different error codes are just different exception raised.

Łukasz Rogalski
  • 18,883
  • 6
  • 53
  • 84