Sep-29-2018, 10:56 PM
You can do something terrible like this
from copy import copy class Greeter: def __init__(self, to): self.to = to def hello(self): return "Hello, {}!".format(to) class Magic: def __init__(self, instance, enclosing_locals): self.instance = instance self.enclosing_locals = enclosing_locals self.origin_enclosing_locals = copy(enclosing_locals) def __enter__(self): for key in dir(self.instance): self.enclosing_locals[key] = getattr(self.instance, key) def __exit__(self, type, value, traceback): for key in list(self.enclosing_locals.keys()): del self.enclosing_locals[key] self.enclosing_locals.update(self.origin_enclosing_locals) with Magic(Greeter("world"), locals()): print(hello())I bet there's a way to not require the locals() call but I couldn't figure it out in a few minutes' Googling. Note that I'm messing with scopes such that any new variables defined within the with-block which would normally be available after the block, won't be. Anyone familiar with Python reading your code would be confused unnecessarily.