Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The latter uses a Python context manager to open the file, the former doesn't. By using the open() context manager like this, you don't need to worry about closing the file yourself, since the context manager takes care of it. The code that runs inside the 'with' block gets yielded inside the context manager. The former version of the code does not store a reference to the file handle, thus cannot close the file handle. Of course you can close file handles without using a context manager too:

  f = open('foo.txt')
  contents = f.read()
  f.close()
But I'd prefer this way:

  with open('foo.txt') as f:
    contents = f.read()
Context managers can of course be used for all kinds of things. For more information, see https://docs.python.org/2/library/contextlib.html


The equivalent code with out the context manager is actually this:

  f = open('foo.txt')
  try:
     contents = f.read()
  finally:
     f.close()
So yes, extra reason to prefer the context manager.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: