Skip to content
Advertisement

How to define enum values that are functions?

I have a situation where I need to enforce and give the user the option of one of a number of select functions, to be passed in as an argument to another function:

I really want to achieve something like the following:

JavaScript

So the following can be executed:

JavaScript

Advertisement

Answer

Your assumption is wrong. Values can be arbitrary, they are not limited to integers. From the documentation:

The examples above use integers for enumeration values. Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. In the vast majority of use-cases, one doesn’t care what the actual value of an enumeration is. But if the value is important, enumerations can have arbitrary values.

However the issue with functions is that they are considered to be method definitions instead of attributes!

JavaScript

You can work around this by using a wrapper class or just functools.partial or (only in Python2) staticmethod:

JavaScript

Sample run:

JavaScript

Or using a wrapper class:

JavaScript

Also note that if you want you can define the __call__ method in your enumeration class to make the values callable:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement