Should use a ‘with’ statement¶
ID: py/should-use-with
Kind: problem
Security severity:
Severity: recommendation
Precision: very-high
Tags:
- maintainability
- readability
- convention
Query suites:
- python-security-and-quality.qls
Click to see the query in the CodeQL repository
The with
statement was introduced by PEP343 to allow standard uses of try-finally
statements to be factored out. Using this simplification makes code easier to read.
Recommendation¶
Review the code and determine whether or not the try-finally
is used only to ensure that a resource is closed. If the only purpose is to ensure that a resource is closed, then replace the try-finally
statement with a with
statement.
Example¶
The following code shows examples of different ways of ensuring that a file is always closed, even when an error is generated. In the second example, the try-finally
block is replaced by a simpler with
statement.
f = open("filename")
try: # Method of ensuring file closure
f.write(...)
finally:
f.close()
with open("filename") as f: # Simpler method of ensuring file closure
f.write(...)
References¶
Python Language Reference: The with statement.
Python Standard Library: Context manager .
Python PEP 343: The “with” Statement.