Search code examples
pythonwith-statementcontextmanager

How should I return interesting values from a with-statement?


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:

  • singletons

    sort of globals...

  • tuple as an argument to the context manager

    makes the function more specific to a problem /less reusable

  • instance that holds the specific attributes as an argument to the context manager

    same problems as the tuple, but more legible

  • raise an exception at the end of the context manager holding the values.

    really bad idea


Solution

  • 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.