Skip to content

Commit 598a33b

Browse files
committed
enh: dyn._asdict now returns a live view (using collections.ChainMap)
1 parent 8bba0b3 commit 598a33b

1 file changed

Lines changed: 4 additions & 6 deletions

File tree

unpythonic/dynassign.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
__all__ = ["dyn", "make_dynvar"]
55

66
import threading
7+
from collections import ChainMap
78

89
# Each new thread, when spawned, inherits the contents of the main thread's
910
# dynamic scope stack.
@@ -91,6 +92,7 @@ def main():
9192
https://stackoverflow.com/questions/2001138/how-to-create-dynamical-scoped-variables-in-python
9293
"""
9394
def __getattr__(self, name):
95+
# Essentially, _asdict() and look up, but without creating the ChainMap every time.
9496
for scope in reversed(_getstack()):
9597
if name in scope:
9698
return scope[name]
@@ -120,19 +122,15 @@ def __contains__(self, name):
120122

121123
# iteration
122124
def _asdict(self):
123-
data = {}
124-
data.update(_global_dynvars)
125-
for scope in _getstack():
126-
data.update(scope)
127-
return data
125+
return ChainMap(*(list(reversed(_getstack())) + [_global_dynvars]))
128126

129127
def __iter__(self):
130128
return iter(self._asdict())
131129
# no __next__, iterating over dict.
132130

133131
def items(self):
134132
"""Like dict.items(), but a snapshot (won't reflect later changes)."""
135-
return self._asdict().items() # TODO: implement a live-update view to dyn, like dict has
133+
return self._asdict().items()
136134

137135
def __len__(self):
138136
return len(self._asdict())

0 commit comments

Comments
 (0)