Can I store persistent variables in my hooks?

Sometimes it might be useful to be able to store values in a hook and then retrieve the value when the hook next gets run.
As the hook is a class, you might think to set a variable on the instance something like:

self.my_var = "something important"

However, this may not work. It actually depends on how the app treats and calls the hooks. Usually, the hook instances are not kept and get re-instantiated each time the hook gets executed.

For example, most apps will call the deprecated Application.execute_hook or the newer Application.execute_hook_method which will not return back the hook, but rather the value that is returned from executing the method on the Hook. So each time the app executes the hook a new hook instance is generated.

However, the Publish2 app, for example, keeps hold of the “publish plugin” hook instances for later use, by using the Application.create_hook_instance method. So in this situation, users are able to store values to the publish plugin, and they will be kept for as long at that publish plugin is kept in the publish tree.

If you need to store a variable persistently between hook executions, you could perhaps store the value in an environment variable, or store it as a class variable on the Hook.
In the case of the class variable, if you take the workfiles2 scene operation hook as an example you could do something like the following:

# create a counter that adds one each time the hook is executed.
if hasattr(SceneOperation, "my_persistent_var"):
    SceneOperation.my_persistent_var += 1
else:
    SceneOperation.my_persistent_var = 1

self.logger.info("my_persistent_var: %s" % SceneOperation.my_persistent_var)
1 Like