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