On Wed, Mar 17, 2021, 5:34 AM Serhiy Storchaka <storchaka@gmail.com> wrote:
12.03.21 23:48, Ethan Furman пише:
> A question that comes up quite a bit on Stackoverflow is how to test to
> see if a value will result in an Enum member, preferably without having
> to go through the whole try/except machinery.
>
...
> Thoughts?

The Enum class is already too overloaded. I sometimes think about adding
SimpleEnum class with minimal simple functionality which would allow to
use enums in more modules sensitive to import time.

As for solving your problem, try/except looks the best solution to me.

    try:
        Color(1)
    except ValueError:
        ... # invalid color
    else:
        ... # valid color

If you don't like try/except, the second best solution is to add a
module level helper in the enum module:

    def find_by_value(cls, value, default=None):
        try:
            return cls(value)
        except ValueError:
            return default

You can add also find_all_by_value(), get_aliases(), etc. It is
important that they are module-level function, so they do not spoil the
namespace of the Enum class.


+1 on a module level helper. 

The preponderance of stackoverflow questions seem convincing enough that people want to do this and it seems like a reasonable request. And I have wanted to do something like this myself, so I'd probably use it. I see it as analogous to situations when you want to use dict.get(key) instead of dict[key].

But adding a non-dunder method to the Enum class namespace seems more suboptimal to me compared to a module level helper, because of the namespace spoiling/crowding issue. No matter what method name were to be chosen, someone at some point would want to use it as an Enum member name (unless of course it's a reserved dunder method).