[Python-ideas] Callable Enum values

Stephan Hoyer shoyer at gmail.com
Fri Apr 21 12:04:45 EDT 2017


On Thu, Apr 20, 2017 at 10:58 AM, Ethan Furman <ethan at stoneleaf.us> wrote:

> I'm curious, what did you find ugly with:
>
>     class TestEnum(CallableEnum):
>
>          @enum
>          def hello(text):
>              "a pleasant greeting"
>              print('hello,', text)
>
>          @enum
>          def goodbye(text):
>              print('goodbye,', text)
>

Yeah, this is actually pretty reasonable.

For my use case, both the functions and their names are pretty long, so I
wouldn't want to write them inside the enum class. With a
decorator/function wrapper, it just gets kind of long -- especially if I
only import modules as required
<https://google.github.io/styleguide/pyguide.html?showone=Imports#Imports>
by the Google style guide. So my real usage looks more like:

class Greeting(callable_enum.Enum):
    HELLO = callable_enum.Value(_greet_hello)
    GOODBYE = callable_enum.Value(_greet_goodbye)
    TO_PYTHON_IDEAS = callable_enum.Value(_welcome_to_python_ideas)

The large callable_enum.Value() wrappers make it harder to track what's
going on.

But perhaps this is really just a good use for an inline declaration, where
I don't need the wrappers at all:

Greeting = callable_enum.Enum('Greeting', {
    'HELLO': _greet_hello,
    'GOODBYE': _greet_goodbye,
    'TO_PYTHON_IDEAS': _welcome_to_python_ideas,
})
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170421/fdca3674/attachment.html>


More information about the Python-ideas mailing list