Replace old function with the new function. Args: origin_func_path (str): original function path rewrite_func (Callable): function to replace with origin_func (Callable): function to replace
(origin_func_path: str | None, rewrite_func: Callable, origin_func: Callable = None)
| 27 | |
| 28 | |
| 29 | def _set_func(origin_func_path: str | None, rewrite_func: Callable, origin_func: Callable = None): |
| 30 | """Replace old function with the new function. |
| 31 | |
| 32 | Args: |
| 33 | origin_func_path (str): original function path |
| 34 | rewrite_func (Callable): function to replace with |
| 35 | origin_func (Callable): function to replace |
| 36 | """ |
| 37 | # import module |
| 38 | if isinstance(origin_func_path, str): |
| 39 | split_path = origin_func_path.split('.') |
| 40 | for i in range(len(split_path), 0, -1): |
| 41 | try: |
| 42 | exec('import {}'.format('.'.join(split_path[:i]))) |
| 43 | break |
| 44 | except Exception: |
| 45 | continue |
| 46 | |
| 47 | origin_func = eval(origin_func_path) \ |
| 48 | if origin_func is None else origin_func |
| 49 | |
| 50 | method_class = inspect.ismethod(origin_func) |
| 51 | |
| 52 | # replace method |
| 53 | if not method_class: |
| 54 | import gc |
| 55 | refs = gc.get_referrers(origin_func) |
| 56 | obj_id = id(origin_func) |
| 57 | for ref in refs: |
| 58 | if isinstance(ref, dict): |
| 59 | for x, y in ref.items(): |
| 60 | if id(y) == obj_id: |
| 61 | ref[x] = rewrite_func |
| 62 | elif isinstance(ref, MutableSequence): |
| 63 | for i, v in enumerate(ref): |
| 64 | if id(v) == obj_id: |
| 65 | ref[i] = rewrite_func |
| 66 | if isinstance(origin_func_path, str): |
| 67 | exec(f'{origin_func_path} = rewrite_func') |
| 68 | elif method_class: |
| 69 | raise NotImplementedError |
| 70 | |
| 71 | return origin_func |
| 72 | |
| 73 | |
| 74 | @contextmanager |
no test coverage detected