Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Enum __call__ method

Tags:

python

enums

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

like image 562
Jacques Gaudin Avatar asked Oct 16 '25 10:10

Jacques Gaudin


1 Answers

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.

like image 84
Ethan Furman Avatar answered Oct 19 '25 02:10

Ethan Furman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!