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

1import inspect 

2 

3 

4# Source: https://www.fast.ai/2019/08/06/delegation/ 

5 

6 

7def delegates(to_function=None, keep=False): 

8 """Decorator: replace `**kwargs` in signature with params from `to`""" 

9 

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 

29 

30 return _f 

31 

32 

33def custom_dir(custom_c, add): 

34 """Custom dir *add description?""" 

35 return dir(type(custom_c)) + list(custom_c.__dict__.keys()) + add 

36 

37 

38class GetAttr: 

39 

40 """ 

41 Base class for attr accesses in `self._xtra` passed down to `self.default 

42 """ 

43 

44 @property 

45 def _xtra(self): 

46 return [o for o in dir(self.default) if not o.startswith("_")] 

47 

48 def __getattr__(self, k): 

49 if k in self._xtra: 

50 return getattr(self.default, k) 

51 raise AttributeError(k) 

52 

53 def __dir__(self): 

54 return custom_dir(self, self._xtra)