Skip to content

Commit 5e6eb53

Browse files
committed
add custom dict item setter
1 parent a24e04b commit 5e6eb53

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

src/psij/job_spec.py

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,23 @@
77
from psij.utils import path_object_to_full_path as o2p
88

99

10+
class _EnvDict(dict):
11+
12+
def __init__(self, *args, **kwargs):
13+
14+
super().__init__(*args, **kwargs)
15+
16+
def __setitem__(self, k, v):
17+
18+
if not isinstance(k, str):
19+
raise TypeError('environment key "%s" is not a string (%s)'
20+
% (k, type(k).__name__))
21+
if not isinstance(v, str):
22+
raise TypeError('environment key "%s" has non-string value (%s)'
23+
% (k, type(v).__name__))
24+
super().__setitem__(k, v)
25+
26+
1027
class JobSpec(object):
1128
"""A class to hold information about the characteristics of a:class:`~psij.Job`."""
1229

@@ -116,15 +133,12 @@ def environment(self) -> Optional[Dict[str, str]]:
116133

117134
@environment.setter
118135
def environment(self, environment: Optional[Dict[str, str]]) -> None:
119-
if environment is not None:
136+
if environment is None:
137+
self._environment = None
138+
else:
139+
self._environment = _EnvDict()
120140
for k, v in environment.items():
121-
if not isinstance(k, str):
122-
raise TypeError('environment key "%s" is not a string (%s)'
123-
% (k, type(k).__name__))
124-
if not isinstance(v, str):
125-
raise TypeError('environment key "%s" has non-string value (%s)'
126-
% (k, type(v).__name__))
127-
self._environment = environment
141+
self._environment[k] = v
128142

129143
@property
130144
def to_dict(self) -> Dict[str, Any]:

tests/test_job_spec.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ def test_environment_types() -> None:
1616
spec = JobSpec()
1717
spec.environment = {'foo': 1} # type: ignore
1818

19+
with pytest.raises(TypeError):
20+
spec = JobSpec()
21+
spec.environment = {'foo': 'bar'}
22+
spec.environment['buz'] = 2 # type: ignore
23+
1924
spec = JobSpec()
2025
assert spec.environment is None
2126

@@ -28,3 +33,5 @@ def test_environment_types() -> None:
2833

2934
spec.environment = {'foo': 'biz'}
3035
assert spec.environment['foo'] == 'biz'
36+
37+
test_environment_types()

0 commit comments

Comments
 (0)