Should use a ‘with’ statement¶
ID: py/should-use-withKind: problemSecurity severity: Severity: recommendationPrecision: very-highTags: - quality - maintainability - readabilityQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
Thewith statement was introduced by PEP343 to allow standard uses oftry-finally statements to be factored out. Using this simplification makes code easier to read.
Recommendation¶
Review the code and determine whether or not thetry-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 thetry-finally statement with awith 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, thetry-finally block is replaced by a simplerwith statement.
f=open("filename")try:# Method of ensuring file closuref.write(...)finally:f.close()withopen("filename")asf:# Simpler method of ensuring file closuref.write(...)
References¶
Python Language Reference:The with statement.
Python Standard Library:Context manager.
Python PEP 343:The “with” Statement.