Is there a better way than using globals to get interesting values from a context manager?
@contextmanager
def transaction():
global successCount
global errorCount
try:
yield
except:
storage.store.rollback()
errorCount += 1
else:
storage.store.commit()
successCount += 1
Other possibilities:
sort of globals...
makes the function more specific to a problem /less reusable
same problems as the tuple, but more legible
really bad idea
See http://docs.python.org/reference/datamodel.html#context-managers
Create a class which holds the success and error counts, and which implements the __enter__
and __exit__
methods.
I still think you should be creating a class to hold you error/success counts, as I said in you last question. I'm guessing you have your own class, so just add something like this to it:
class transaction:
def __init__(self):
self.errorCount = 0
self.successCount = 0
def __enter__(*args):
pass
def __exit__(self, type, value, traceback):
if type:
storage.store.rollback()
self.errorCount += 1
else:
storage.store.commit()
self.successCount += 1
(type
is None if there are no exceptions once invoking the contextmanager
)
And then you probably are already using this somewhere, which will invoke the contextmanager
and run your __exit__()
code. Edit: As Eli commented, only create a new transaction instance when you want to reset the coutners.
t = transaction()
for q in queries:
with t:
t.execute(q)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With