On 3/12/21 2:49 PM, Ricky Teachey wrote:
On Fri, Mar 12, 2021 at 4:52 PM Ethan Furman wrote:
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.
Could this be an instance where match-case might become the canonical solution? I'm probably getting the syntax wrong, but maybe it would be something like: match value: case MyEnum(): assert isinstance(value, MyEnum) case _: assert not isinstance(value, MyEnum)
The use case is when you have an unknown value that may or may not convert into an Enum member. So a three-member Enum would look something like: ```python match value: case MyEnum(): pass case 1|2|3: value = MyEnum(value) case _: handle_error_or_use_default() ``` Seven lines of code. try/except would be something like: ```python try: value = MyEnum(value) except ValueError: handle_error_or_use_default() ``` vs what I'm envisioning: ```python value = MyEnum.get(value, some_default) ``` or maybe ```python value = MyEnum.get(value) if value is None: handle_error() ``` -- ~Ethan~ _______________________________________________ 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/Z7C36KHOFDDM6REA4PN6GPPYOJ22DPBY/ Code of Conduct: http://python.org/psf/codeofconduct/