Skip to content

Miscellaneous Utilities

call_once

call_once(func)

Decorator that ensures a function is called only once during the lifetime of a process, across all threads.

If multiple threads call the decorated function simultaneously, only one thread (the "leader") will execute the function. Other threads will wait for the leader to finish and then return the same result.

If the function raises an exception, the same exception will be re-raised in all threads.

Example

The expensive_initialization_function below will be called only once, even if it is called from multiple threads concurrently.

from cereggii import call_once

@call_once
def expensive_initialization_function():
    pass

Since you may want the function to be unit-tested and wrapping it in a decorator may make things awkward, you can wrap it after the definition:

from cereggii import call_once

def _expensive_initialization_function():
    pass

expensive_initialization_function = call_once(_expensive_initialization_function)

Parameters:

  • func

    The function to be called once.

Returns:

  • A wrapper function that ensures func is executed only once.