Source code for nrv.backend._inouts
from collections.abc import Callable
from inspect import getcallargs
from copy import deepcopy
import inspect
from ._log_interface import rise_warning
[docs]
def set_attributes(my_object, attributes_dict):
"""
Set existing attributes of an object from a dictionary.
Parameters
----------
my_object : object
Object whose attributes should be updated.
attributes_dict : dict
Mapping from attribute names to new values.
Returns
-------
int
Always returns ``0``.
"""
for key, value in attributes_dict.items():
if key in my_object.__dict__:
setattr(my_object, key, value)
else:
rise_warning(
"trying to set a non existing attribute "
+ str(key)
+ " in "
+ str(type(my_object))
)
return 0
[docs]
def check_function_kwargs(func: Callable, kwargs: dict) -> dict:
"""
check that the keys of a dictionnary are arguments of a function and return an updated dictionnary with only valide keys
Parameters
----------
func : function
function to check
kwargs : dict
dictionnary of arguments to check
Returns
-------
dict
updated kwargs dictionnary
"""
func_kwargs_set = set(func.__code__.co_varnames[: func.__code__.co_argcount])
kwargs_set = set(kwargs.keys())
not_valid_kwargs_set = kwargs_set - func_kwargs_set
for k in not_valid_kwargs_set:
kwargs.pop(k)
return kwargs
[docs]
def function_to_str(func: Callable) -> str:
"""
Return the source code corresponding to a callable.
Parameters
----------
func : Callable
Callable object to serialize.
Returns
-------
str
Source code of the callable.
"""
lines = inspect.getsource(func)
return lines
[docs]
def str_to_function(lines: str) -> Callable:
"""
Placeholder converting a serialized function back to a callable.
Parameters
----------
lines : str
Serialized function representation.
Returns
-------
Callable
Currently returns ``lines`` unchanged.
"""
lines
return lines