Content deleted Content added
→Basic techniques: Remove the "def work_with_file" lines which are not useful |
mNo edit summary |
||
Line 36:
==Basic techniques==
The basic approach to resource management is to acquire a resource, do something with it, then release it, yielding code of the form (illustrated with opening a file in Python):
<syntaxhighlight lang="python">
f = open(filename)
...
Line 46:
The resource leak can be resolved in languages that support a <code>finally</code> construction (like Python) by placing the body in a <code>try</code> clause, and the release in a <code>finally</code> clause:
<syntaxhighlight lang="python">
f = open(filename)
try:
Line 54:
</syntaxhighlight>
This ensures correct release even if there is a return within the body or an exception thrown. Further, note that the acquisition occurs ''before'' the <code>try</code> clause, ensuring that the <code>finally</code> clause is only executed if the <code>open</code> code succeeds (without throwing an exception), assuming that "no exception" means "success" (as is the case for <code>open</code> in Python). If resource acquisition can fail without throwing an exception, such as by returning a form of <code>null</code>, it must also be checked before release, such as:
<syntaxhighlight lang="python">
f = open(filename)
try:
Line 63:
</syntaxhighlight>
While this ensures correct resource management, it fails to provide adjacency or encapsulation. In many languages there are mechanisms that provide encapsulation, such as the <code>with</code> statement in Python:
<syntaxhighlight lang="python">
with open(filename) as f:
...
Line 130:
By contrast, in Python, a [https://docs.python.org/3/library/csv.html#csv.reader csv.reader] does not own the <code>file</code> that it is reading, so there is no need (and it is not possible) to close the reader, and instead the <code>file</code> itself must be closed.<ref>[https://stackoverflow.com/questions/3216954/python-no-csv-close Python: No csv.close()?]</ref>
<syntaxhighlight lang="
with open(filename) as f:
r = csv.reader(f)
|