On Jan 28, 2012, at 6:42 AM, Greg Landrum wrote:
> I haven't followed the evolution of context managers in Python; what's
> the advantage?

The context manager reduces duplication (and generally saves a couple of lines 
of code) for a common idiom, and makes it easier to do resource management 
where a "start()" call must always be matched by an "end()" call.

Context managers are syntax abstractions for the common pattern pattern of:
  - set things up before you run code
  - tear them down after you are done
  - possibly do something else when there's an exception
 
The justification document is at http://www.python.org/dev/peps/pep-0343/
and the "What's New" description at
  http://docs.python.org/whatsnew/2.5.html#pep-343-the-with-statement

Here are some examples of it in use, where I compare the old and new way. 


  == Make sure that a file is closed, even on error

  # old style (works, but depends on the garbage collector for the close) 

f = open(filename)
... do stuff with f ...

  # old style (makes sure the file is always closed) 

f = open(filename)
try:
  ... do stuff with f ...
finally:
  f.close()  # Make sure it's closed at the end

  # with a context manager (close f at the end of the block)

with open(filename) as f:
  ... do stuff with f ...


  == Acquire and release a critical lock

  # old style

write_lock = threading.Lock()
...
write_lock.acquire()
try:
  .. do critical code ...
finally:
  write_lock.release()


  # new style
  
write_lock = threading.Lock()
...
with write_lock:
  .. do critical code


  == Handle a database transaction but rollback if there are errors

  # old style

try:
  ... work with the database here ..
except:
  cursor.rollback()
  raise
else:
  cursor.commit()

  # new style
with connection:
  ... work with the database here ..

  == My test code captures the value of stdout with 

  # old style
old_stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
try:
  run_test()
finally:
  output = sys.stdout.getvalue()
  sys.stdout = old_stdout


  # new style

with CaptureStdout() as new_stdout:
  run_test()
output = new_stdout.getvalue()






                                Andrew
                                [email protected]



------------------------------------------------------------------------------
Try before you buy = See our experts in action!
The most comprehensive online learning library for Microsoft developers
is just $99.99! Visual Studio, SharePoint, SQL - plus HTML5, CSS3, MVC3,
Metro Style Apps, more. Free future releases when you subscribe now!
http://p.sf.net/sfu/learndevnow-dev2
_______________________________________________
Rdkit-discuss mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/rdkit-discuss

Reply via email to