Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python content manager executing order
import contextlib
@contextlib.contextmanager
def inner():
try:
print("inner(): before yield")
yield "~~~message~~~"
print("inner(): after yield")
except Exception as e:
print("inner(): catch exception -- "+str(e))
raise
@contextlib.contextmanager
def middle():
print("middle(): enter method")
try:
with inner() as message:
print("middle(): before yield")
yield message
print("middle(): after yield")
except Exception as e:
print("middle(): catch exception -- "+str(e))
raise
@contextlib.contextmanager
def outer():
print("outer(): enter method")
try:
with middle() as message:
print("outer(): before yield")
yield message
print("outer(): after yield")
except Exception as e:
print("outer(): catch exception -- "+str(e))
raise
print("module: enter")
try:
with outer() as message:
print("module: enter with block")
print("module: message: "+message)
raise Exception("module: raise exception")
print("module: leave with block")
except Exception as e:
print("module: catch exception -- "+str(e))
raise
print("module: leave")
"""
module: enter
outer(): enter method
middle(): enter method
inner(): before yield
middle(): before yield
outer(): before yield
module: enter with block
module: message: ~~~message~~~
inner(): catch exception -- module: raise exception
middle(): catch exception -- module: raise exception
outer(): catch exception -- module: raise exception
module: catch exception -- module: raise exception
Traceback (most recent call last):
File "/Users/cynthia/Documents/contextmanager.py", line 42, in <module>
raise Exception("module: raise exception")
Exception: module: raise exception
"""
import contextlib
@contextlib.contextmanager
def inner():
print("inner(): before yield")
yield "~~~message~~~"
print("inner(): after yield")
@contextlib.contextmanager
def middle():
print("middle(): enter method")
with inner() as message:
print("middle(): before yield")
yield message
print("middle(): after yield")
@contextlib.contextmanager
def outer():
print("outer(): enter method")
with middle() as message:
print("outer(): before yield")
yield message
print("outer(): after yield")
print("module: enter")
with outer() as message:
print("module: enter with block")
print("modele: message: "+message)
print("module: leave with block")
print("module: leave")
"""
module: enter
outer(): enter method
middle(): enter method
inner(): before yield
middle(): before yield
outer(): before yield
module: enter with block
modele: message: ~~~message~~~
module: leave with block
outer(): after yield
middle(): after yield
inner(): after yield
module: leave
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.