My mistake, instead perhaps something like this, it is not built-in:
class ContextTester(object):
"""Initialize context environment and replace variables when completed"""
def __init__(self, locals_reference):
self.prev_local_variables = locals_reference.copy()
self.locals_reference = locals_reference
def __enter__(self):
pass
def __exit__(self, exception_type, exception_value, traceback):
self.locals_reference.update(self.prev_local_variables)
a = 5
def do_some_work():
global a
print(a)
a = 8
print("Before context tester: {}".format(a))
with ContextTester(locals()) as context:
print("In context tester before assignment: {}".format(a))
a = 6
do_some_work()
print("In context tester after assignment: {}".format(a))
print("After context tester: {}".format(a))
Output:
Before context tester: 5
In context tester before assignment: 5
6
In context tester after assignment: 8
After context tester: 5
For clarity, so you know it's actually doing something:
class ContextTester(object):
"""Initialize context environment and replace variables when completed"""
def __init__(self, locals_reference):
self.prev_local_variables = locals_reference.copy()
self.locals_reference = locals_reference
def __enter__(self):
pass
def __exit__(self, exception_type, exception_value, traceback):
#self.locals_reference.update(self.prev_local_variables)
pass
a = 5
def do_some_work():
global a
print(a)
a = 8
print("Before context tester: {}".format(a))
with ContextTester(locals()) as context:
print("In context tester before assignment: {}".format(a))
a = 6
do_some_work()
print("In context tester after assignment: {}".format(a))
print("After context tester: {}".format(a))
a = 5
print("Before context tester: {}".format(a))
with ContextTester(locals()) as context:
print("In context tester before assignment: {}".format(a))
a = 6
print("In context tester after assignment: {}".format(a))
print("After context tester: {}".format(a))
Output:
Before context tester: 5
In context tester before assignment: 5
6
In context tester after assignment: 8
After context tester: 8
Before context tester: 5
In context tester before assignment: 5
In context tester after assignment: 6
After context tester: 6
You could also do this:
def wrapper_function(func, *args, **kwargs):
prev_globals = globals().copy()
func(*args, **kwargs)
globals().update(prev_globals)
It should be noted that if you try to use the with statement within a function, you'll want to use globals() as the reference to locals and it may have unintended consequences, might still anyways.
I wouldn't recommend doing this at all, but should work.
with Namespace() as ns:
to have a little closure or whatever it is, and then return to the parent namespace after execution. (i'm not a computer scientist - someone correct me if i'm not using these words correctly) – Weslee