Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd recommend using Python's <code>with</code> statement for managing resources that need to be cleaned up. The problem with using an explicit <code>close()</code> statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a <code>finally</code> block to prevent a resource leak when an exception occurs.</p> <p>To use the <code>with</code> statement, create a class with the following methods:</p> <pre><code> def __enter__(self) def __exit__(self, exc_type, exc_value, traceback) </code></pre> <p>In your example above, you'd use </p> <pre><code>class Package: def __init__(self): self.files = [] def __enter__(self): return self # ... def __exit__(self, exc_type, exc_value, traceback): for file in self.files: os.unlink(file) </code></pre> <p>Then, when someone wanted to use your class, they'd do the following:</p> <pre><code>with Package() as package_obj: # use package_obj </code></pre> <p>The variable package_obj will be an instance of type Package (it's the value returned by the <code>__enter__</code> method). Its <code>__exit__</code> method will automatically be called, regardless of whether or not an exception occurs.</p> <p>You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the <code>with</code> clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the <code>__enter__</code> and <code>__exit__</code> methods. Then, the Package class would be defined strictly inside the <code>__enter__</code> method and returned. That way, the caller never could instantiate the Package class without using a <code>with</code> statement:</p> <pre><code>class PackageResource: def __enter__(self): class Package: ... self.package_obj = Package() return self.package_obj def __exit__(self, exc_type, exc_value, traceback): self.package_obj.cleanup() </code></pre> <p>You'd use this as follows:</p> <pre><code>with PackageResource() as package_obj: # use package_obj </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload