Skip to content

Commit 7e6363b

Browse files
AugProsloria
andauthored
Implemented subcast_key on dict (#152)
* implemented subcast_key on dict * Add TODO to rename arg * Fix typing * Update changelog Co-authored-by: Steven Loria <sloria1@gmail.com>
1 parent 542017a commit 7e6363b

3 files changed

Lines changed: 22 additions & 7 deletions

File tree

CHANGELOG.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Changelog
22

3+
## 7.4.0 (unreleased)
4+
5+
- Add `subcast_key` argument to `env.dict` ([#151](https://github.com/sloria/environs/issues/151)).
6+
Thanks [AugPro](https://github.com/AugPro) for the suggestion and PR.
7+
38
## 7.3.1 (2020-03-22)
49

510
- Fix error when parsing empty list with subcast
@@ -240,7 +245,3 @@ Bug fixes:
240245
## 0.1.0 (2016-04-25)
241246

242247
- First PyPI release.
243-
244-
```
245-
246-
```

environs/__init__.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,13 +143,19 @@ def _preprocess_list(value: typing.Union[str, typing.Iterable], **kwargs) -> typ
143143

144144

145145
def _preprocess_dict(
146-
value: typing.Union[str, typing.Mapping[str, _T]], subcast: Subcast, **kwargs
147-
) -> typing.Mapping[str, _T]:
146+
value: typing.Union[str, typing.Mapping],
147+
# TODO: Rename subcast to subcast_values and re-order arguments for next major release
148+
subcast: Subcast,
149+
subcast_key: Subcast = None,
150+
**kwargs
151+
) -> typing.Mapping:
148152
if isinstance(value, Mapping):
149153
return value
150154

151155
return {
152-
key.strip(): subcast(val.strip()) if subcast else val.strip()
156+
(subcast_key(key.strip()) if subcast_key else key.strip()): (
157+
subcast(val.strip()) if subcast else val.strip()
158+
)
153159
for key, val in (item.split("=") for item in value.split(",") if value)
154160
}
155161

tests/test_environs.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,14 @@ def test_dict_with_subcast(self, set_env, env):
107107
set_env({"DICT": "key1=1,key2=2"})
108108
assert env.dict("DICT", subcast=int) == {"key1": 1, "key2": 2}
109109

110+
def test_dict_without_subcast_key(self, set_env, env):
111+
set_env({"DICT": "1=value1,2=value2"})
112+
assert env.dict("DICT") == {"1": "value1", "2": "value2"}
113+
114+
def test_dict_with_subcast_key(self, set_env, env):
115+
set_env({"DICT": "1=value1,2=value2"})
116+
assert env.dict("DICT", subcast_key=int) == {1: "value1", 2: "value2"}
117+
110118
def test_dict_with_default_from_string(self, set_env, env):
111119
assert env.dict("DICT", "key1=1,key2=2") == {"key1": "1", "key2": "2"}
112120

0 commit comments

Comments
 (0)