C. Loew C. Loew - 10 months ago 103
Python Question

Python 3 Enums with Function Values

I noticed an oddity in the Python 3 Enums (link).

If you set the value of an Enum to a function, it prevents the attribute from being wrapped as an Enum object, which prevents you from being able to use the cool features like

to dynamically load the attribute.

Is this a bug? Done on purpose?

I searched for a while but found no mention of restricted values that you can use in an Enum.

Here is sample code that displays the issue:

class Color(Enum):
Red = lambda: print('In Red')
Blue = lambda: print('In Blue')

print(Color.Red) # <function> - should be Color.Red via Docs
print(Color.Blue) # <function> - should be Color.Bluevia Docs
print(Color['Red']) # throws KeyError - should be Color.Red via Docs

Also, this is my first time asking, so let me know if there's anything I should be doing differently! And thanks for the help!

Answer Source

The documentation says:

The rules for what is allowed are as follows: _sunder_ names (starting and ending with a single underscore) are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of __dunder__ names and descriptors (methods are also descriptors).

A "method" is just a function defined inside a class body. It doesn't matter whether you define it with lambda or def. So your example is the same as:

class Color(Enum):
    def Red():
        print('In Red')
    def Blue():
        print('In Blue')

In other words, your purported enum values are actually methods, and so won't become members of the Enum.