CodeQL documentation

Should use a ‘with’ statement

ID: py/should-use-with
Kind: problem
Security severity: 
Severity: recommendation
Precision: very-high
Tags:
   - quality
   - maintainability
   - readability
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

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy