Merge pull request #5097 from wumode/refector-check_method

This commit is contained in:
jxxghp
2025-11-05 23:15:24 +08:00
committed by GitHub
3 changed files with 72 additions and 29 deletions
+28 -29
View File
@@ -1,5 +1,7 @@
import ast
import dis
import inspect
import textwrap
from types import FunctionType
from typing import Any, Callable, get_type_hints
@@ -39,45 +41,42 @@ class ObjectUtils:
return len(list(parameters.keys()))
@staticmethod
def check_method(func: FunctionType) -> bool:
def check_method(func: Callable[..., Any]) -> bool:
"""
检查函数是否已实现
"""
try:
# 尝试通过源代码分析
source = inspect.getsource(func)
in_comment = False
for line in source.split('\n'):
line = line.strip()
# 跳过空行
if not line:
src = inspect.getsource(func)
tree = ast.parse(textwrap.dedent(src))
node = tree.body[0]
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
return True
body = node.body
for stmt in body:
# 跳过 pass
if isinstance(stmt, ast.Pass):
continue
# 处理"""单行注释
if (line.startswith(('"""', "'''"))
and line.endswith(('"""', "'''"))
and len(line) > 3):
continue
# 处理"""多行注释
if line.startswith(('"""', "'''")):
in_comment = not in_comment
continue
# 在注释中则跳过
if in_comment:
continue
# 跳过#注释、pass语句、装饰器、函数定义行
if (line.startswith('#')
or line == "pass"
or line.startswith('@')
or line.startswith('def ')):
continue
# 发现有效代码行
# 跳过 docstring 或 ...
if isinstance(stmt, ast.Expr):
expr = stmt.value
if isinstance(expr, ast.Constant):
if isinstance(expr.value, str) or expr.value is Ellipsis:
continue
# 检查 raise NotImplementedError
if isinstance(stmt, ast.Raise):
exc = stmt.exc
if isinstance(exc, ast.Call) and getattr(exc.func, "id", None) == "NotImplementedError":
continue
if isinstance(exc, ast.Name) and exc.id == "NotImplementedError":
continue
return True
# 没有有效代码行
return False
except Exception as err:
print(err)
# 源代码分析失败时,进行字节码分析
code_obj = func.__code__
code_obj = func.__code__ # type: ignore[attr-defined]
instructions = list(dis.get_instructions(code_obj))
# 检查是否为仅返回None的简单结构
if len(instructions) == 2: