Skip to content

Commit

Permalink
✨ 为mixin.replaces添加self参数检查,避免意外绑定到非成员函数或遗漏self参数
Browse files Browse the repository at this point in the history
  • Loading branch information
yanang007 committed Sep 15, 2024
1 parent 40707a1 commit c19f33e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
6 changes: 5 additions & 1 deletion metalpy/mexin/injectors/replaces.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions metalpy/mexin/injectors/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c19f33e

Please sign in to comment.