Skip to content

Comments

Use with to automatically close file#1

Open
bowbahdoe wants to merge 1 commit intoHalophilus:mainfrom
bowbahdoe:patch-1
Open

Use with to automatically close file#1
bowbahdoe wants to merge 1 commit intoHalophilus:mainfrom
bowbahdoe:patch-1

Conversation

@bowbahdoe
Copy link

@bowbahdoe bowbahdoe commented Apr 28, 2022

The pattern of

file = open("path", "r")
# ... do stuff with file ...
file.close()

Is subtly flawed in that if an error happens between opening the file and closing it, you will never reach the line that closes the file. This doesn't matter if the next thing your code does is crash entirely, but if you have a longer running app (like a web server) then this would be a "resource leak"

When you do

with open("path", "r") as file:
    # ... do stuff with file ...

Then no matter what happens, Python will close the file when you exit that block

The pattern of 

```python
file = open("path", "r")
# ... do stuff with file ...
file.close()
```

Is subtly flawed in that if an error happens between opening the file and closing it, you will never reach the line that closes the file. This doesn't matter if the next thing your code does is crash entirely, but if you have a longer running app (like a web server) then this would be a "resource leak"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant