With-blocks as a proper way to manage (open/close) file resources


The concern is documenting the control flow structure known as with-block that replaces the need to pair each open() with

1. usual pattern

  • the pattern of working with the files where you
  • The close is important as it informs the operating system that the work with the file has been finished
  • It closes the handle and releases the file for further use
  • Also, it saves the changes — without closing, it is possible to lose data
  • there may be pending writes buffered up that may not get written completely
  • Or, when opening lots of files, the system may run out of resources
  • The mechanism that pairs open() with close() is similar to garbage collector mechanisms in languages without memory management

2. enter with-block

  • any objects that support he context-manager protocol — file objects are one of them
  • it exploits the context-protocol nature of the file object
  • it uses the with clause
  • the aim is to get rid of the need to close the resource explicitly
  • this is error-prone and even if it is not forgotten, one must use try-catch-finallly block to handle exceptions
  • the with construct calls it for us

3. zen of python

  • this also resonates with the first aphorism of the zen of python: Beautiful is better than ugly which, here, is taking precedence over Explicit is better than implicit

4. comparative linguistics: this is similar to using in c-sharp

5. sources

Technical Support Engineer of a Data Collection Platform (Snowplow Analytics)