Associate Python Enum with a function and make it Callable

When you want to choose an algorithm from several options, you may want to associate a function with each value of an enumeration type.

In Java you can set a method for each value of an enum, but in Python you can't. Let's think about how to write it neatly in the direction of making Enum itself Callable.

If the value doesn't matter

Python Enums can be set freely. Therefore, the value itself should be a function.

However, the function defined in the class that inherits Enum is judged as a method and will not be included in the listed values.

class Dame(Enum):
    #You're not defining a value, you're defining a method
    A = lambda: print("A")

list(Dame)
#Empty list

So, I borrowed this stackoverflow idea and decided to use the tuple containing the function as the value.

from enum import Enum

class CallableEnum(Enum):
    """
Inherit this class to create a Callable Enum
    """
    def __call__(self, *args,**kwargs):
        return self.value[0](*args,**kwargs)

def register(func):
    """
Decorator to easily define tuples that contain functions
    """
    return func,

Here's how to use it.

class Test(CallableEnum):
    @register
    def A():
        print("A")
    
    @register
    def B():
        print("B")

Test.A()
# A

If you want to set the value freely

Give the class T that inherits Enum a dictionary from T to the function, and refer to it in __call __.

However, if "T to function dictionary "is included as an attribute of T in the class definition, it will also be one of the enumerated values. You have to add it after T is completed as a class.

Therefore, it is a way to add a function after the class definition is finished.

from enum import Enum

class Dnum(Enum):
    """
Dispatching Enum. Inherit this guy
    """
    @classmethod
    def register(cls, key):
        if not hasattr(cls, "table"):
            cls.table = {}
        def registration(func):
            cls.table[key] = func
        return registration
    
    def __call__(self, *args,**kwargs):
        return self.__class__.table[self](*args,**kwargs)


def register(enum):
    def ret(func):
        enum.__class__.register(enum)(func)
    return ret

Use it like this.

from enum import auto

class Test(Dnum):
    A = "A"
    B = "B"

@register(Test.A)
def _A():
    print("A")

@register(Test.B)
def _B():
    print("B")

Test.A()
# A

Is there a trick to write a function in the class definition while setting the value freely?

Recommended Posts

Associate Python Enum with a function and make it Callable
Make a decision tree from 0 with Python and understand it (4. Data structure)
Make a fortune with Python
[Practice] Make a Watson app with Python! # 2 [Translation function]
Let's make a simple game with Python 3 and iPhone
Load a photo and make a handwritten sketch. With zoom function. Tried to make it.
Let's make a GUI with python.
[Python] Make the function a lambda function
Make a recommender system with python
Let's make a graph with python! !!
How to make a surveillance camera (Security Camera) with Opencv and Python
Make a simple OMR (mark sheet reader) with Python and OpenCV
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
I tried to make a periodical process with Selenium and Python
Make a scraping app with Python + Django + AWS and change jobs
Create a Python function decorator with Class
Fractal to make and play with Python
A memo with Python2.7 and Python3 on CentOS
Let's make a voice slowly with Python
Let's make a web framework with Python! (1)
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
Deploy a Python app on Google App Engine and integrate it with GitHub
Set up a Lambda function and let it work with S3 events!
Create a decision tree from 0 with Python and understand it (5. Information Entropy)
[Python] I introduced Word2Vec and played with it.
Make a Twitter trend bot with heroku + Python
[Python] Make a game with Pyxel-Use an editor-
Building a python environment with virtualenv and direnv
I want to make a game with Python
Try to make a "cryptanalysis" cipher with Python
I tried function synthesis and curry with python
[Python] Make a simple maze game with Pyxel
Launch a web server with Python and Flask
Let's replace UWSC with Python (5) Let's make a Robot
Let's write a Python program and run it
Try to make a dihedral group with Python
[# 1] Make Minecraft with Python. ~ Preliminary research and design ~
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
Make a thermometer with Raspberry Pi and make it visible on the browser Part 3
Make a Python program a daemon and run it automatically when the OS starts
Divide each PowerPoint slide into a JPG file and output it with python
WEB scraping with python and try to make a word cloud from reviews
Get the stock price of a Japanese company with Python and make a graph
Make a function decorator
Make one repeating string with a Python regular expression.
Build a python virtual environment with virtualenv and virtualenvwrapper
Let's make a Makefile and build it (super beginner)
Install selenium on Mac and try it with python
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Make a simple Slackbot with interactive button in python
[Let's play with Python] Make a household account book
[# 2] Make Minecraft with Python. ~ Model drawing and player implementation ~
Make a breakpoint on the c layer with python
Make a function to describe Japanese fonts with OpenCV
Crawling with Python and Twitter API 1-Simple search function
I made a LINE BOT with Python and Heroku
Build a python virtual environment with virtualenv and virtualenvwrapper
Make a CSV formatting tool with Python Pandas PyInstaller
Get mail from Gmail and label it with Python3