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 re
Solution 1:
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 = Truetry:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = Falseifnot exit(mgr, *sys.exc_info()):
raise# The exception is swallowed if exit() returns truefinally:
# The normal and non-local-goto cases are handled hereif exc:
exit(mgr, None, None, None)
Solution 2:
Read http://www.python.org/dev/peps/pep-0343/ it explains what the with statement is and how it looks in try .. finally
form.
Post a Comment for "Confused About Python's With Statement"