Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about Python's with statement

Tags:

python

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

  • what is the with statement
  • and the "as" statement here
  • and best practices to translate between both forms
  • what kinds of classes lend them to with blocks

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.

like image 886
Jesvin Jose Avatar asked Aug 01 '11 12:08

Jesvin Jose


People also ask

What is the use of with statement in Python?

with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner.

What is Contextmanager Python?

If you have used the with statement in Python then chances are you've already used a context manager. A context manager usually takes care of setting up some resource, e.g. opening a connection, and automatically handles the clean up when we are done with it. Probably, the most common use case is opening a file.

Which of the following Python keyword is used for context management?

Python provides an easy way to manage resources: Context Managers. The with keyword is used. When it gets evaluated it should result in an object that performs context management.


1 Answers

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)
like image 151
Roman Bodnarchuk Avatar answered Sep 21 '22 03:09

Roman Bodnarchuk