Project

General

Profile

Support #22470

Use of Python constructs when possible to help context managers to properly manage resources.

Added by Lorena Lobato Pardavila about 2 months ago. Updated 22 days ago.

Status:
Work in progress
Priority:
Normal
Category:
-
Target version:
Start date:
04/29/2019
Due date:
% Done:

0%

Estimated time:
Stakeholders:
Duration:

Description

We can improve the performance (and reduce code) with the with Statement and Context Managers when files are being managed.
Currently, close() is called on every file opened, and some times the file is in a function that may raise an exception or has multiple return paths, using for this try...except.
We could use 'with' statement that clarifies code that previously would use try...finally blocks to ensure all resources we use are properly cleaned up, regardless of if the code returns or an exception is thrown: context managers.
For example:

    # old file exists, check if same content
    fl = open(fname, 'r')
    try:
        old_data = fl.read()
    finally:
         fl.close()

We could do :

with open(fname,'r') as fl
 fd.read()

and not needed to close the files and the block is calling it automatically.

To DO: Review the code and do the replacement where this case is satisfied.

Note: It works with open(). But not with os.open() as it is just a wrapper for the lower-level POSIX syscall. It returns the file descriptor (a number) that represents the opened file and not a file object: so we cannot use it in this case.

History

#1 Updated by Lorena Lobato Pardavila about 2 months ago

  • Target version set to v3_5

#2 Updated by Lorena Lobato Pardavila about 1 month ago

  • Target version changed from v3_5 to v3_5_1

#3 Updated by Lorena Lobato Pardavila 22 days ago

  • Status changed from New to Work in progress
  • Tracker changed from Idea to Support


Also available in: Atom PDF