Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom dict delimiter #277

Merged
merged 1 commit into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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