safe_call#
- deeptrack.utils.safe_call(function: Callable[[...], Any], positional_args: list[Any] | None = None, **kwargs: Any) Any#
Calls a function with valid arguments from a dictionary of arguments.
Filters kwargs to include only arguments accepted by the function, ensuring that no invalid arguments are passed. This function also supports positional arguments.
Parameters#
- function: Callable[…, Any]
The function to call.
- positional_args: list[Any] | None, optional
List of positional arguments to pass to the function. Defaults to None.
- **kwargs: Any
Dictionary of keyword arguments to filter and pass.
Returns#
- Any
The result of calling the function with the filtered arguments.
Examples#
from deeptrack.utils import safe_call
Basic usage with positional and keyword arguments:
>>> def f(a, b=2, c=3): ... return a + b + c
>>> safe_call(f, positional_args=[1], b=4, x=100) 8
All keyword arguments:
>>> safe_call(f, a=1, b=2, c=3) 6
Extra keyword arguments (ignored if not accepted by the function):
>>> safe_call(f, a=2, extra=42) 7
Missing required argument (raises TypeError):
>>> safe_call(f, b=2, c=3) Traceback (most recent call last): ... TypeError: ...
Function with *args and **kwargs (the kwargs are not passed):
>>> def g(a, *args, b=5, **kwargs): ... return a, args, b, kwargs
>>> safe_call(g, positional_args=[1, 10], b=7, x=3, y=2) (1, (10,), 7, {})
Function with only *args (positional):
>>> def h(*args): ... return args
>>> safe_call(h, positional_args=[1, 2, 3]) (1, 2, 3)
Function with only **kwargs (the kwargs are not passed):
>>> def i(**kwargs): ... return sorted(kwargs.items())
>>> safe_call(i, foo=1, bar=2) []