Finalizers

When writing models it can be useful to have functions that will be run at the end of the compilation. A typical use case is making sure all resources are properly flushed back and all connections are properly closed. To help with this, finalizers can be used.

Adding new finalizers

A finalizer is a python function that is registered by using the finalizer() function as decorator or as callback. This function should be a function that doesn’t take arguments and that doesn’t return anything. Functions registered this way will be call when the compiler finishes (with no guarantee on the execution order).

an example of a finalizer that will close an open connection using the decorator option requires the following code:

 1from inmanta import compiler
 2
 3connection = None
 4
 5def get_connection():
 6   global connection
 7   if connection is None:
 8        connection = connect()
 9   return connection
10
11@compiler.finalizer
12def finalize_connection():
13   if connection:
14      connection.close()

the same example but using the callback option would look like this:

 1from inmanta import compiler
 2
 3connection = None
 4
 5def get_connection():
 6  global connection
 7  if not connection:
 8       connection = connect()
 9       compiler.finalizer(finalize_connection)
10   return connection
11
12def finalize_connection():
13   if connection:
14      connection.close()