Skip to content

Commit

Permalink
Update _base.py
Browse files Browse the repository at this point in the history
  • Loading branch information
fkiraly committed Aug 18, 2024
1 parent 633f910 commit b16c43b
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions skbase/base/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1294,21 +1294,45 @@ def _get_fitted_params_default(self, obj=None):
]

def getattr_safe(obj, attr):
"""Get attribute of object, safely.
Safe version of getattr, that returns None if attribute does not exist,
or if an exception is raised during getattr.
Also returns a boolean indicating whether the attribute was successfully
retrieved, to distinguish between None value and non-existent attribute,
or exception during getattr.
Parameters
----------
obj : any object
object to get attribute from
attr : str
attribute name to get from obj
Returns
-------
attr : Any
attribute of obj, if it exists and does not raise on getattr;
otherwise None
success : bool
whether the attribute was successfully retrieved
"""
try:
if hasattr(obj, attr):
attr = getattr(obj, attr)
return attr, True
else:
return None, False
except Exception:
return None, False

fitted_param_dict = {}

for p in fitted_params:
attr, success = getattr_safe(obj, p)
if not success:
continue
p_name = p[:-1] # remove the "_" at the end to get the parameter name
fitted_param_dict[p_name] = attr
if success:
p_name = p[:-1] # remove the "_" at the end to get the parameter name
fitted_param_dict[p_name] = attr

return fitted_param_dict

Expand Down

0 comments on commit b16c43b

Please sign in to comment.