10

I've found a simply way to implement(hack) an enum into Python:

class MyEnum:
  VAL1, VAL2, VAL3 = range(3)

I can then call this as such:

bob = MyEnum.VAL1

Sexy!

Alright, now I want to be able to get both the numerical value if given a string, or a string if given a numerical value. Let's say I want the strings to exactly match up to the Enum key's

The best I could think of is something like this:

class MyEnum:
  VAL1, VAL2, VAL3 = range(3)
  @classmethod
  def tostring(cls, val):
    if (val == cls.VAL1):
      return "VAL1"
    elif (val == cls.VAL2):
      return "VAL2"
    elif (val == cls.VAL3):
      return "VAL3"
    else:
      return None
  @classmethod
  def fromstring(cls, str):
    if (str.upper() == "VAL1"):
      return cls.VAL1
    elif (str.upper() == "VAL2"):
      return cls.VAL2
    elif (str.upper() == "VAL2"):
      return cls.VAL2
    else:
      return None

or something like that (ignore how i'm catching invalid cases)

Is there a better, more python centric way to do what I'm doing above? Or is the above already as concise as it gets.

It seems like there's got to be a better way to do it.

3

7 Answers 7

23

[Time passes...]

The new Python Enum has finally landed in 3.4, and has also been backported. So the answer to your question is now to use that. :)


An example:

>>> from enum import Enum
>>> class Modes(Enum) :
...    Mode1 = "M1"
...    Mode2 = "M2"
...    Mode3 = "M3"
...

>>> Modes.Mode1
<Modes.Mode1: 'M1'>

>>> Modes.Mode1.value
'M1'

>>> Modes.Mode1.value
'M1'

>>> Modes['Mode1']    # index/key notation for name lookup
<Modes.Mode1: 'M1'>

>>> Modes('M1')       # call notation for value lookup
<Modes.Mode1: 'M1'>

>>> Modes("XXX")      # example error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda3\lib\enum.py", line 291, in __call__
    return cls.__new__(cls, value)
  File "C:\Anaconda3\lib\enum.py", line 533, in __new__
    return cls._missing_(value)
  File "C:\Anaconda3\lib\enum.py", line 546, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 'XXX' is not a valid Modes
11

Well, here is what you asked for:

class MyEnum:
  VAL1, VAL2, VAL3 = range(3)
  @classmethod
  def tostring(cls, val):
    for k,v in vars(cls).iteritems():
        if v==val:
            return k

  @classmethod
  def fromstring(cls, str):
      return getattr(cls, str.upper(), None)

print MyEnum.fromstring('Val1')
print MyEnum.tostring(2)

But I really don't get the point of Enums in Python. It has such a rich type system as well as generators and coroutines to manage states.

I know I've not been using Enums in Python for more than 12 years, maybe you can get rid of them too ;-)

11
  • MyEnum.tostring(3) returns None. I should probably be MyEnum.tostring(MyEnum.VAL3)
    – Rod
    Dec 17, 2010 at 17:22
  • That's because range starts at 0. tostring(2) gives VAL3. Unfortunate names (*[1-9]). Afaik, C/C++ enum starts at 0 too.
    – user395760
    Dec 17, 2010 at 17:25
  • 2
    "tostring" and "fromsring" are certainly javesque. Python does not need this cruft.
    – jsbueno
    Dec 17, 2010 at 21:09
  • 8
    If enums aren't of any use in Python, it's odd how so many people have felt a need to implement something like them over the years. One way I personally use them is to give names to things like magic numbers and make my scripts more descriptive and readable.
    – martineau
    Dec 18, 2010 at 5:05
  • 6
    Not only is it odd how many people have felt a need to implement them; they somehow ended up in the standard library! Clearly there's quite a utility for them. Mar 27, 2015 at 17:37
7

Use a dict:

MyEnum = {'VAL1': 1, 'VAL2':2, 'VAL3':3}

No classes necessary. Dicts have your class beat because 1.) they're incredibly efficient, 2.) have a bunch of incredible methods baked in, and 3.) are a universal language construct. They're also extensible:

MyEnum['VAL4'] = 4

It's not wise to implement C++ (or another language's) functionality in Python. If you find yourself "hacking up an enum" or something of that nature, you can bet the farm you're not doing it the Python way.

If you want to go the opposite way, build another dict. (e.g. {'1':'VAL1', ...}

2
  • 3
    If I have to build a 2nd dictionary to go the other way, that violates the single-point-of-definition value preferred in any language. How do you respond to that concern?
    – Stabledog
    May 14, 2012 at 14:07
  • 1
    Extensibility is not a feature for enums. Apr 18, 2015 at 15:29
3

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

This one is interesting:

class EnumMeta(type):
  def __getattr__(self, name):
    return self.values.index(name)

  def __setattr__(self, name, value):  # this makes it read-only
    raise NotImplementedError

  def __str__(self):
    args = {'name':self.__name__, 'values':', '.join(self.values)}
    return '{name}({values})'.format(**args)

  def to_str(self, index):
    return self.values[index]

class Animal(object):
  __metaclass__ = EnumMeta
  values = ['Horse','Dog','Cat']

Use:

In [1]: Animal.to_str(Animal.Dog)
Out[1]: 'Dog'
In [2]: Animal.Dog
Out[2]: 1
In [3]: str(Animal)
Out[3]: 'Animal(Horse, Dog, Cat)'

It's simple and lightweight. Are they any disadvantages of this approach?

EDIT: AFAIK enums are not very pythonic as a concept, thats why they were not implemented in the first place. I never used them, and can't see any usecase for them in Python. Enums are useful in static typed languages, because they are not dynamic ;)

3

This will do what you want and generalizes your implementation slightly reducing boiler-plate code:

class EnumBase: # base class of all Enums
    @classmethod
    def tostring(cls, value):
        return dict((v,k) for k,v in cls.__dict__.iteritems())[value]

    @classmethod
    def fromstring(cls, name):
        return cls.__dict__[name]

class MyEnum(EnumBase): VAL1, VAL2, VAL3 = range(3)

print MyEnum.fromstring('VAL1')
# 0
print MyEnum.tostring(1)
# VAL2
1

You could use dictionaries:

class MyEnum:
    VAL1, VAL2, VAL3 = range(3)
    __toString = { VAL1 : "VAL1", VAL2 : "VAL2", VAL3 : "VAL3" }

    @classmethod
    def tostring(cls, val):
        return cls.__toString.get(val)

    @classmethod
    def fromstring(cls, str):
        i = str.upper()
        for k,v in cls.__toString.iteritems():
            if v == i:
                return k
        return None


print MyEnum.tostring(MyEnum.VAL1)
print MyEnum.fromstring("VAL1")

Edit : THC4k answers is definitely better. But left mine as an example of naive implementation.

2
  • 2
    Leading double underscores (= name mangling) are... well, not evil, but I never saw that hypothetical case where they have a small benefit, as opposed to use usual case where they just break stuff.
    – user395760
    Dec 17, 2010 at 17:40
  • @delnan. I will take note of this.
    – Rod
    Dec 17, 2010 at 17:46
0

You should not have to hardcode your values inside the class - you better have an enumerator factory. WHile at that, just add some nicetirs provided by Python, for example, override the represntation method, or attribute getting:

class Enumerator(object):
    def __init__(self, *names):
        self._values = dict((value, index) for index, value in enumerate (names))
    def __getattribute__(self, attr):
        try:
            return object.__getattribute__(self,"_values")[attr]
        except KeyError:
            return object.__getattribute__(self, attr)
    def __getitem__(self, item):
        if isinstance (item, int):
            return self._values.keys()[self._values.values().index(item)]
        return self._values[item]
    def __repr__(self):
        return repr(self._values.keys())

Now just use that:

>>> enum = Enumerator("val1", "val2", "val3")
>>> enum
['val3', 'val2', 'val1']
>>> enum.val2
1
>>> enum["val1"]
0
>>> enum[2]
'val3'

(btw, people in the Python developers list are talking about this,most likely we will have a more complete, and with enough features, implementation of this natively by Python 3.3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.