Skip to content

Commit

Permalink
feat: Support enum type (#1313)
Browse files Browse the repository at this point in the history
People came up with the idea of using the available parameters ... Never
noticed so far

https://github.com/viur-framework/viur-shop/blob/ff6ea1721c7e09f4c3a9cd3346541f071884c2fb/src/viur/shop/modules/api.py#L176
  • Loading branch information
sveneberth authored Nov 11, 2024
1 parent 8bbb839 commit 73944e8
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/viur/core/module.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
import enum
import inspect
import types
import typing as t
Expand Down Expand Up @@ -81,6 +82,8 @@ def parse_value_by_annotation(annotation: type, name: str, value: str | list | t
Tries to parse a value according to a given type.
May be called recursively to handle unions, lists and tuples as well.
"""
# logging.debug(f"{annotation=} | {name=} | {value=}")

# simple types
if annotation is str:
return str(value)
Expand Down Expand Up @@ -128,6 +131,15 @@ def parse_value_by_annotation(annotation: type, name: str, value: str | list | t

return parse_value_by_annotation(int | str, name, value)

elif isinstance(annotation, enum.EnumMeta):
try:
return annotation(value)
except ValueError as exc:
for value_, member in annotation._value2member_map_.items():
if str(value) == str(value_): # Do a string comparison, it could be a IntEnum
return member
raise errors.NotAcceptable(f"{' '.join(exc.args)} for {name}") from exc

raise errors.NotAcceptable(f"Unhandled type {annotation=} for {name}={value!r}")

# examine parameters
Expand Down

0 comments on commit 73944e8

Please sign in to comment.