Source code for package_name_to_import_with.garbage_collection_module
1"""Define top level decorator."""
2import collections.abc
3import functools
4import gc
5import typing
6
7import pydantic
8
9FunctionType: typing.TypeAlias = collections.abc.Callable[..., typing.Any]
10
11
[docs]
12@pydantic.validate_call(validate_return=True)
13def define_garbage_collection_decorator(
14 function_to_be_decorated: FunctionType,
15) -> FunctionType: # pragma: no cover
16 """Perform forcefully garbage collection after execution of provided function.
17
18 Parameters
19 ----------
20 function_to_be_decorated : FunctionType
21 function whose execution may require forceful garbage collection
22
23 Returns
24 -------
25 FunctionType
26 decorated function
27 """
28
29 @functools.wraps(function_to_be_decorated)
30 def wrapper_function(*args: typing.Any, **kwargs: typing.Any) -> typing.Any: # noqa: ANN401
31 """Execute provided function with forceful garbage collection afterwards.
32
33 Parameters
34 ----------
35 *args : tuple
36 positional arguments for ``function_to_be_decorated``
37 **kwargs : dict
38 keyword arguments for ``function_to_be_decorated``
39
40 Returns
41 -------
42 typing.Any
43 output of the provided function with provided arguments
44 """
45 result = function_to_be_decorated(*args, **kwargs)
46 _ = gc.collect()
47
48 return result
49
50 return wrapper_function