Confused about Python with expression

I saw the 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 the __ enter__ and __ exit__ methods, and they are really useful in forms with "file_pointer:" or "with lock:". But no literature ever enlightens. And various examples show inconsistency when the translation is between the form “c” and the ordinary form (yes, its subjective).

Explain, please

  • what is the with statement
  • and the like operator here
  • and best practices for translating between both forms
  • which classes provide them with blocks

Epilogue

http://effbot.org/zone/python-with-statement.htm . , . https://stackoverflow.com/users/190597/unutbu, , .

+5
2

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)
+9
+2

All Articles