deeptrack.utils Module#
Utility functions for argument handling and signature inspection.
This module provides utility functions to enhance code readability, streamline common operations, and ensure type and argument consistency when working with functions, methods, and callables in Python.
Key Features#
Method Detection
Check if an object has a callable method with a given name.
List Conversion
Ensure that any input is represented as a list.
Signature Inspection
Retrieve the names of arguments a function accepts, and check for default values.
Safe Function Calling
Call a function by passing only arguments accepted by its signature.
Module Structure#
Functions:
hasmethod(obj, method_name) -> bool
Checks whether an object has a callable method named method_name.
as_list(obj) -> list[Any]
Ensures that the input is a list, wrapping if necessary.
get_kwarg_names(function) -> list[str]
Retrieves the names of the keyword arguments accepted by a function.
kwarg_has_default(function, argument) -> bool
Checks whether a specific argument of a function has a default value.
safe_call(function, positional_args=None, **kwargs) -> Any
Calls a function, passing only valid arguments from a dictionary.
Examples#
>>> import deeptrack as dt
Check if a method exists in an object:
>>> class Example:
... def foo(self): pass
>>> dt.utils.hasmethod(Example(), "foo")
True
>>> dt.utils.hasmethod(Example(), "bar")
False
Convert various objects to lists:
>>> dt.utils.as_list(42)
[42]
>>> dt.utils.as_list((1, 2))
[1, 2]
>>> dt.utils.as_list("abc")
['abc']
Retrieve keyword argument names from a function:
>>> def func(x, y=1, z=2):
... pass
>>> dt.utils.get_kwarg_names(func)
['x', 'y', 'z']
Check if a function argument has a default value:
>>> def func(x, y=1):
... pass
>>> dt.utils.kwarg_has_default(func, "x")
False
>>> dt.utils.kwarg_has_default(func, "y")
True
Safely call a function with extra arguments:
>>> def f(a, b=2, c=3):
... return a + b + c
>>> dt.utils.safe_call(f, positional_args=[1], b=5, x=100)
9
Functions#
|
Ensure that the input is a list. |
|
Retrieve the names of the keyword arguments accepted by a function. |
|
Check whether an object has a callable method named method_name. |
|
Check whether a specific argument of a function has a default value. |
|
Calls a function with valid arguments from a dictionary of arguments. |