"getting the block of commands that are to be executed in the with statement" Code Answer

2

try this.

import sys 
class mynamespace(object):
    def __init__(self,ns):
        self.ns = ns
    def __enter__(self):
        globals().update(self.ns)
    def __exit__(self, exc_type,exc_value,traceback):
        self.ns.update(sys._getframe(1).f_locals)

my_dict = {'a':3, 'b':2} 
with mynamespace(my_dict) as ns:
    print(a) # should print 3
    x = 5 # when the block finishes, my_dict['x'] should now be 5 

print(my_dict['x'])
By majjam on January 25 2022

Answers related to “getting the block of commands that are to be executed in the with statement”

Only authorized users can answer the Search term. Please sign in first, or register a free account.