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. > > A couple versions ago one could use a containment check: > > if 1 in Color: > > but than was removed as Enums are considered containers of members, not > containers of the member values. It was also possible to define one's > own `_missing_` method and have it return None or the value passed in, > but that has also been locked down to either return a member or raise an > exception. > > At this point I see three options: > > 1) add a `get(value, default=None)` to EnumMeta (similar to `dict.get()` > > 2) add a recipe to the docs > > 3) do nothing > > 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. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/PLCJCLTU5FZDHVMJW3BN7FQVD6BPNJBY/ Code of Conduct: http://python.org/psf/codeofconduct/