GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Should use a ‘with’ statement — CodeQL query help 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-code-quality.qls
   - 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.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.