gilbert189 @gilbert189
class Scope:
	def __init__(self, shadow=...):
		self.shadow = shadow

	def __enter__(self):
		self.globals = dict(globals())

	def __exit__(self, exc_type, exc_value, traceback):
		glb_keys = set(globals().keys())
		for diff in glb_keys - self.globals.keys():
			del globals()[diff]
		if self.shadow is not None:
			for key in self.globals.keys():
				if self.shadow is ... or key in self.shadow:
					globals()[key] = self.globals[key]

foo = 1
bar = 2
print("before scope:", foo, bar)
with Scope(shadow=("bar",)):
	foo *= -1
	bar *= -1
	baz = 3
	print("in scope:", foo, bar)
print("after scope:", foo, bar)

assert "baz" not in globals()
Feb 5, 2024, 1:57 PM
0

comments