Skip to content

Commit 8115a2c

Browse files
committed
enh: make env a MutableMapping
1 parent 6117020 commit 8115a2c

3 files changed

Lines changed: 19 additions & 7 deletions

File tree

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,8 @@ When the `with` block exits, the environment clears itself. The environment inst
247247

248248
*Changed in v0.13.1.* ``env`` now provides the ``collections.abc.Mapping`` API.
249249

250+
*Changed in v0.14.0.* ``env`` now provides also the ``collections.abc.MutableMapping`` API.
251+
250252

251253
### ``assignonce``
252254

unpythonic/collections.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,9 @@ def doit(x):
9191
for elt in y:
9292
x.add(elt)
9393
return x
94-
elif isinstance(x, MutableMapping):
94+
# env provides the MutableMapping API, but shouldn't get the general treatment here.
95+
# (This is important for the lazify macro.)
96+
elif isinstance(x, MutableMapping) and not isinstance(x, env):
9597
y = {k: doit(v) for k, v in x.items()}
9698
x.clear()
9799
x.update(y)

unpythonic/env.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
__all__ = ["env"]
55

6-
from collections.abc import Container, Sized, Iterable, Mapping
6+
from collections.abc import Container, Sized, Iterable, Mapping, MutableMapping
77

88
class env:
99
"""Environment for let-like constructs.
@@ -116,6 +116,18 @@ def __eq__(self, other):
116116
def __len__(self):
117117
return len(self._env)
118118

119+
# MutableMapping
120+
def pop(self, k, *default):
121+
return self._env.pop(k, *default)
122+
def popitem(self):
123+
return self._env.popitem()
124+
def clear(self):
125+
return self._env.clear()
126+
def update(self, mapping, **bindings):
127+
return self._env.update(mapping, **bindings)
128+
def setdefault(self, k, *default):
129+
return self._env.setdefault(k, *default)
130+
119131
# subscripting
120132
def __getitem__(self, k):
121133
return getattr(self, k)
@@ -167,10 +179,6 @@ def __lshift__(self, arg):
167179
self.set(name, value)
168180
return self
169181

170-
def clear(self):
171-
"""Clear the environment, i.e. forget all bindings."""
172-
self._env = {}
173-
174182
def finalize(self):
175183
"""Finalize environment.
176184
@@ -217,6 +225,6 @@ def finalize(self):
217225
# return _assignonce_wrapper(obj) # copy-construct obj with wrapper
218226

219227
# register virtual base classes
220-
for abscls in (Container, Sized, Iterable, Mapping):
228+
for abscls in (Container, Sized, Iterable, Mapping, MutableMapping):
221229
abscls.register(env)
222230
del abscls

0 commit comments

Comments
 (0)