Message Boards Message Boards

3
|
3778 Views
|
1 Reply
|
6 Total Likes
View groups...
Share
Share this post:

Call automatic cleanup code when an expression goes out of scope.

Posted 4 years ago

The package ExpressionCleanup described below is available on github. It contains the functions AddCleanupFunction and Cleanup. I'm open to suggestions for better names or more natural call signatures.

AddCleanupFunction[expr, func] will call func when all references to expr are gone.

Cleanup[expr] will call any cleanup code that has been registered for expr, and Cleanup[] will call all registered cleanup code. All cleanup code is called when the kernel exits cleanly.

Note that 'references' includes anything in the output history, anything accessible via % or Out[..]. In the example below, $HistoryLength is set to zero otherwise Out[4] would have kept the expression still available.

In[1]:= PacletDirectoryLoad[pathToGitCheckout];

In[2]:= << ExpressionCleanup`
(*library will be built if need be*)

In[3]:= $HistoryLength = 0

Out[3]= 0

In[4]:= f = {1, 2, 3}

Out[4]= {1, 2, 3}

In[5]:= AddCleanupFunction[f,
  Print["calling deletion code"];
  Print["use any compound expression"];
]

In[6]:= f =.

During evaluation of In[6]:= calling deletion code

During evaluation of In[6]:= use any compound expression

This example calls simple Print functions for cleanup, but you could imagine using this to close input or output streams, delete temporary files, or unload external libraries.

POSTED BY: Jason Biggs

This function has been added to the Wolfram Language Paclet Repository as part of the WeakCache paclet.

The basic usage is now

PacletInstall["JasonB/WeakCache"];

Needs["JasonB`WeakCache`"]

$HistoryLength = 0;
foo = Range[3];
CleanupAfter[foo, Print["cleaning up after foo"]]

foo =.

cleaning up after foo
POSTED BY: Jason Biggs
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract