From c19f33e63944b3aa8a2039b16f022330d04e7cea Mon Sep 17 00:00:00 2001 From: yanang007 Date: Sun, 15 Sep 2024 19:55:20 +0800 Subject: [PATCH] =?UTF-8?q?:sparkles:=20=E4=B8=BAmixin.replaces=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0self=E5=8F=82=E6=95=B0=E6=A3=80=E6=9F=A5=EF=BC=8C?= =?UTF-8?q?=E9=81=BF=E5=85=8D=E6=84=8F=E5=A4=96=E7=BB=91=E5=AE=9A=E5=88=B0?= =?UTF-8?q?=E9=9D=9E=E6=88=90=E5=91=98=E5=87=BD=E6=95=B0=E6=88=96=E9=81=97?= =?UTF-8?q?=E6=BC=8Fself=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- metalpy/mexin/injectors/replaces.py | 6 +++++- metalpy/mexin/injectors/utils.py | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/metalpy/mexin/injectors/replaces.py b/metalpy/mexin/injectors/replaces.py index 312b6b5..6e6558c 100644 --- a/metalpy/mexin/injectors/replaces.py +++ b/metalpy/mexin/injectors/replaces.py @@ -1,8 +1,8 @@ from typing import Union from .recoverable_injector import RecoverableInjector -from .utils import wrap_method_with_target from .replacement import create_replacement, get_ancestor, get_nest +from .utils import wrap_method_with_target, check_self_parameter class Replaces(RecoverableInjector): @@ -57,6 +57,10 @@ def __call__(self, func): if not self.force_unbound: wrapper, is_method = wrap_method_with_target(self.nest, wrapper) + + if is_method: + check_self_parameter(func) + wrapper = create_replacement(wrapper, orig, self) cmd = f'self.nest.{self.name} = wrapper' exec(cmd) diff --git a/metalpy/mexin/injectors/utils.py b/metalpy/mexin/injectors/utils.py index 502baee..a56d48d 100644 --- a/metalpy/mexin/injectors/utils.py +++ b/metalpy/mexin/injectors/utils.py @@ -17,6 +17,17 @@ def wrap_method_with_target(target, func): return wrapper, is_target_method +def check_self_parameter(func): + sig = inspect.signature(func) + params = list(sig.parameters.values()) + if len(params) == 0 or params[0].name not in ('self', 'this', '_'): + warnings.warn(f"Wrapping method '{func.__name__}' which does not have 'self/this/_' as the first parameter" + f" and unexpected behavior is likely to happen." + f" It is usually resulted by misusing decorators like @replaces," + f" but can also happen in some corner cases." + f" Please report if you think it's intended.") + + def update_params(func, args, kwargs, new_kwargs): """使用new_kwargs更新func的args和kwargs