Skip to content

Commit

Permalink
Customizable dict delimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
gregoiredx committed Oct 21, 2022
1 parent e36f114 commit 990c699
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ The following are all type-casting methods of `Env`:
- `env.float`
- `env.decimal`
- `env.list` (accepts optional `subcast` and `delimiter` keyword arguments)
- `env.dict` (accepts optional `subcast_keys` and `subcast_values` keyword arguments)
- `env.dict` (accepts optional `subcast_keys`, `subcast_values` and `delimiter` keyword arguments)
- `env.json`
- `env.datetime`
- `env.date`
Expand Down
5 changes: 3 additions & 2 deletions environs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ def _preprocess_dict(
subcast_keys: typing.Optional[Subcast] = None,
subcast_key: typing.Optional[Subcast] = None, # Deprecated
subcast_values: typing.Optional[Subcast] = None,
delimiter: str = ",",
**kwargs,
) -> typing.Mapping:
if isinstance(value, Mapping):
Expand All @@ -224,7 +225,7 @@ def _preprocess_dict(

return {
subcast_keys_instance.deserialize(key.strip()): subcast_values_instance.deserialize(val.strip())
for key, val in (item.split("=", 1) for item in value.split(",") if value)
for key, val in (item.split("=", 1) for item in value.split(delimiter) if value)
}


Expand Down Expand Up @@ -352,7 +353,7 @@ class Env:
ma.fields.Dict,
"dict",
preprocess=_preprocess_dict,
preprocess_kwarg_names=("subcast", "subcast_keys", "subcast_key", "subcast_values"),
preprocess_kwarg_names=("subcast", "subcast_keys", "subcast_key", "subcast_values", "delimiter"),
)
json = _field2method(ma.fields.Field, "json", preprocess=_preprocess_json)
datetime = _field2method(ma.fields.DateTime, "datetime")
Expand Down
4 changes: 4 additions & 0 deletions tests/test_environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ def test_dict(self, set_env, env):
set_env({"DICT": "key1=1,key2=2"})
assert env.dict("DICT") == {"key1": "1", "key2": "2"}

def test_dict_with_spaces_as_delimiter(self, set_env, env):
set_env({"DICT": "key1=1 key2=2"})
assert env.dict("DICT", delimiter=" ") == {"key1": "1", "key2": "2"}

def test_dict_with_subcast_values(self, set_env, env):
set_env({"DICT": "key1=1,key2=2"})
assert env.dict("DICT", subcast_values=int) == {"key1": 1, "key2": 2}
Expand Down

0 comments on commit 990c699

Please sign in to comment.