Skip to content

Commit 346cefc

Browse files
committed
Allow __getitem__ to raise the same way os.environ[XXX] would
1 parent fba9587 commit 346cefc

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

easybuild/tools/environment.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,11 +117,24 @@ def apply_context(context=None):
117117
return curr_env
118118

119119

120-
def getvar(key, default=''):
120+
def getvar(key, default='', strict=False):
121121
"""
122122
Return value of key in the environment, or default if not found
123123
"""
124-
return get_context().get(key, os._real_os.environ.get(key, default))
124+
context = get_context()
125+
if key in context:
126+
val = context[key]
127+
if val is None:
128+
if strict:
129+
raise KeyError(f"Key '{key}' is explicitly unset in the current context")
130+
else:
131+
return default
132+
return val
133+
else:
134+
if strict:
135+
return os._real_os.environ[key]
136+
else:
137+
return os._real_os.environ.get(key, default)
125138

126139

127140
@contextmanager
@@ -324,7 +337,7 @@ def sanitize_env():
324337
class MockEnviron(dict):
325338
"""Hook into os.environ and replace it with calls from this module to track changes to the environment."""
326339
def __getitem__(self, key):
327-
return getvar(key)
340+
return getvar(key, strict=True)
328341

329342
def __setitem__(self, key, value):
330343
setvar(key, value, verbose=False, log_changes=False)

0 commit comments

Comments
 (0)