pythonpython-3.xenums

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 EnumCls['AttrName'] 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

Solution

  • 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.