Content deleted Content added
m Reverted edits by 2.28.242.213 (talk) (HG) (3.4.4) |
m →Basic techniques: type hint |
||
Line 37:
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):
<source lang=python>
def work_with_file(filename: str):
f = open(filename)
...
Line 48:
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:
<source lang=python>
def work_with_file(filename: str):
f = open(filename)
try:
Line 57:
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:
<source lang=python>
def work_with_file(filename: str):
f = open(filename)
try:
Line 67:
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:
<source lang=python>
def work_with_file(filename: str):
with open(filename) as f:
...
|