Jesvin Jose
Jesvin Jose

Reputation: 23078

Confused about Python's with statement

I saw some code in the Whoosh documentation:

with ix.searcher() as searcher:
    query = QueryParser("content", ix.schema).parse(u"ship")
    results = searcher.search(query)

I read that the with statement executes __ enter__ and __ exit__ methods and they are really useful in the forms "with file_pointer:" or "with lock:". But no literature is ever enlightening. And the various examples shows inconsistency when translating between the "with" form and the conventional form (yes its subjective).

Please explain


Epilogue

The article on http://effbot.org/zone/python-with-statement.htm has the best explanation. It all became clear when I scrolled to the bottom of the page and saw a familiar file operation done in with. https://stackoverflow.com/users/190597/unutbu ,wish you had answered instead of commented.

Upvotes: 5

Views: 344

Answers (2)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

Example straight from PEP-0343:

with EXPR as VAR:
   BLOCK

#translates to:

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)

Upvotes: 9

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

Read http://www.python.org/dev/peps/pep-0343/ it explains what the with statement is and how it looks in try .. finally form.

Upvotes: 2

Related Questions