Skip to content

Instantly share code, notes, and snippets.

@gvanrossum
Last active August 29, 2015 14:10
Show Gist options
  • Save gvanrossum/291bfcfe70d2f9582331 to your computer and use it in GitHub Desktop.
Save gvanrossum/291bfcfe70d2f9582331 to your computer and use it in GitHub Desktop.
Transaction example
python3 trans.py
begin
initial_preparations
HO HO HO
main: i = 0
finishing_touches
commit
and a bottle of rum 0
begin
initial_preparations
HO HO HO
main: i = 1
commit
and a bottle of rum 1
# With "return" instead of "raise StopIteration" at lines 31-32
python3 trans.py
begin
initial_preparations
HO HO HO
main: i = 0
finishing_touches
commit
and a bottle of rum 0
begin
initial_preparations
HO HO HO
main: i = 1
finishing_touches
commit
# (Note how this doesn't print "and a bottle of rum 1")
import contextlib
def begin(): print('begin')
def rollback(): print('rollback')
def commit(): print('commit')
def initial_preparations(): print('initial_preparations')
def finishing_touches(): print('finishing_touches')
@contextlib.contextmanager
def transaction():
begin()
try:
yield from do_it()
except:
rollback()
raise
else:
commit()
def do_it():
initial_preparations()
yield # Body of with-statement is executed here
finishing_touches()
def gene():
for i in range(2):
with transaction():
print('HO HO HO')
yield i
if i == 1:
# return
raise StopIteration # This is wrong
print('and a bottle of rum', i)
def main():
for i in gene():
print('main: i =', i)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment