I had a feeling there’s an easier way to do this but I implemented this

class Scope:
	def __enter__(self):
		self.glb_keys = set(globals().keys())
		print(self.glb_keys)

	def __exit__(self, exc_type, exc_value, traceback):
		glb_keys = set(globals().keys())
		for diff in glb_keys - self.glb_keys:
			del globals()[diff]

foo = 1
bar = 2
with Scope():
	baz = 3

print(globals().keys())

comments