Coverage for lasso/utils/decorators.py: 0%
28 statements
« prev ^ index » next coverage.py v7.2.4, created at 2023-04-28 18:42 +0100
« prev ^ index » next coverage.py v7.2.4, created at 2023-04-28 18:42 +0100
1import inspect
4# Source: https://www.fast.ai/2019/08/06/delegation/
7def delegates(to_function=None, keep=False):
8 """Decorator: replace `**kwargs` in signature with params from `to`"""
10 def _f(f_att):
11 if to_function is None:
12 to_f, from_f = f_att.__base__.__init__, f_att.__init__
13 else:
14 to_f, from_f = to_function, f_att
15 sig = inspect.signature(from_f)
16 sig_dict = dict(sig.parameters)
17 k = sig_dict.pop("kwargs")
18 s2_dict = {
19 k: v
20 for k, v in inspect.signature(to_f).parameters.items()
21 if v.default != inspect.Parameter.empty and k not in sig_dict
22 }
23 sig_dict.update(s2_dict)
24 if keep:
25 sig_dict["kwargs"] = k
26 # noinspection PyTypeChecker
27 from_f.__signature__ = sig.replace(parameters=sig_dict.values())
28 return f_att
30 return _f
33def custom_dir(custom_c, add):
34 """Custom dir *add description?"""
35 return dir(type(custom_c)) + list(custom_c.__dict__.keys()) + add
38class GetAttr:
40 """
41 Base class for attr accesses in `self._xtra` passed down to `self.default
42 """
44 @property
45 def _xtra(self):
46 return [o for o in dir(self.default) if not o.startswith("_")]
48 def __getattr__(self, k):
49 if k in self._xtra:
50 return getattr(self.default, k)
51 raise AttributeError(k)
53 def __dir__(self):
54 return custom_dir(self, self._xtra)