尝试这个。
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 5print(my_dict['x'])


