Skip to content

Commit b709959

Browse files
committed
Add ignore_case argument to enum parser
1 parent e0c61d7 commit b709959

3 files changed

Lines changed: 29 additions & 6 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ The following are all type-casting methods of `Env`:
103103
- `env.uuid`
104104
- `env.log_level`
105105
- `env.path` (casts to a [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html))
106-
- `env.enum` (casts to any given enum type in `type` keyword argument)
106+
- `env.enum` (casts to any given enum type specified in `type` keyword argument, accepts optional `ignore_case` keyword argument)
107107

108108
## Reading `.env` files
109109

environs/__init__.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -180,11 +180,20 @@ def _preprocess_json(value: str, **kwargs):
180180
_EnumT = typing.TypeVar("_EnumT", bound=Enum)
181181

182182

183-
def _enum_parser(value, *, type: typing.Type[_EnumT], **kwargs) -> _EnumT:
184-
try:
185-
return type[value]
186-
except KeyError:
187-
raise ma.ValidationError(f"Not a valid '{type.__name__}' enum.")
183+
def _enum_parser(value, *, type: typing.Type[_EnumT], ignore_case: bool = False, **kwargs) -> _EnumT:
184+
invalid_exc = ma.ValidationError(f"Not a valid '{type.__name__}' enum.")
185+
186+
if not ignore_case:
187+
try:
188+
return type[value]
189+
except KeyError:
190+
raise invalid_exc
191+
192+
for enum_value in type:
193+
if enum_value.name.lower() == value.lower():
194+
return enum_value
195+
196+
raise invalid_exc
188197

189198

190199
def _dj_db_url_parser(value: str, **kwargs) -> dict:

tests/test_environs.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,20 @@ def test_enum_cast(self, set_env, env):
211211
set_env({"DAY": "SUNDAY"})
212212
assert env.enum("DAY", type=DayEnum) == DayEnum.SUNDAY
213213

214+
def test_enum_cast_ignore_case(self, set_env, env):
215+
set_env({"DAY": "suNDay"})
216+
assert env.enum("DAY", type=DayEnum, ignore_case=True) == DayEnum.SUNDAY
217+
218+
def test_invalid_enum(self, set_env, env):
219+
set_env({"DAY": "suNDay"})
220+
with pytest.raises(environs.EnvError):
221+
assert env.enum("DAY", type=DayEnum)
222+
223+
def test_invalid_enum_ignore_case(self, set_env, env):
224+
set_env({"DAY": "SonDAY"})
225+
with pytest.raises(environs.EnvError):
226+
assert env.enum("DAY", type=DayEnum, ignore_case=True)
227+
214228

215229
class TestEnvFileReading:
216230
def test_read_env(self, env):

0 commit comments

Comments
 (0)