3

I have an Enum like so:

from enum import Enum

class Animal(Enum):

     cat = 'meow'
     dog = 'woof'
     never_heard_of = None

     def talk(self):
         print(self.value)

I would like to override the __call__ method so that a call like Animal('hee-haw') returns Animals.never_heard_of or None instead of raising ValueError. I would rather avoid a try statement everytime I call the Animal.

What would be a pure Python equivalent of Enum.__call__ ?

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
  • Why don't you just use e.g. `dict(cat='meow', dog='woof').get(whatever)`? This seems like a weird use of an enumerator. – jonrsharpe May 25 '16 at 17:33
  • 1
    @jonrsharpe: I was after an immutable set of constants. If a constant is not defined it returns None. I can have logic gates into my program to tell me about which spreadsheet software I will interact with. – Jacques Gaudin May 25 '16 at 17:48
  • Please give some context, otherwise this is likely an [XY problem](http://meta.stackexchange.com/q/66377/248731). – jonrsharpe May 25 '16 at 17:49

1 Answers1

9

Update 2017-03-30

With Python 3.6 (and aenum 2.01) you can specify a _missing_ method that will be called to give your class one last chance before raising ValueError. So now you can do:

    @classmethod
    def _missing_(cls, name):
        return cls.never_heard_of

Original Answer

To be clear: you want the __call__ that is associated with Animal() which is actually on the metaclass (EnumMeta in enum.py).

This is a bag of worms you don't want to get in to, as it is very easy to break things.

See this answer for more details, but the simple solution is to create a get method for your Animal enum:

    @classmethod
    def get(cls, name):
        try:
            return cls[name]
        except KeyError:
            return cls.never_heard_of

and then Animal.get('wolf') will return Animal.never_heard_of.


1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Community
  • 1
  • 1
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237