, @Martijn Pieters answer. , sys.modules , , .
, . mod.py:
import sys
class MyModule(object):
def __enter__(self):
print("__enter__<")
def __exit__(self, *exc):
print("__exit__> {0}".format(exc))
_ref = sys.modules[__name__]
sys.modules[__name__] = MyModule()
:
import mod
with mod:
print('running within context')
:
__enter__<
running within context
__exit__> (None, None, None)
. , _ref.