Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

executor() 方法中的 annotations 检查与 from __future__ import annotations 不兼容 #25

Open
RockChinQ opened this issue Feb 12, 2024 · 0 comments

Comments

@RockChinQ
Copy link
Contributor

for name, annotation, default in ParamSignatures:
if default:
if isinstance(default, Depend):
if not inspect.isclass(default.func):
depend_func = default.func
elif hasattr(default.func, "__call__"):
depend_func = default.func.__call__
else:
raise TypeError("must be callable.")
if depend_func in lru_cache_sets and default.cache:
depend_func = lru_cache_sets[depend_func]
else:
if default.cache:
original = depend_func
if inspect.iscoroutinefunction(depend_func):
depend_func = alru_cache(depend_func)
else:
depend_func = lru_cache(depend_func)
lru_cache_sets[original] = depend_func
CallParams[name] = await self.executor_with_middlewares(
depend_func, default.middlewares, event_context, lru_cache_sets
)
continue
else:
raise RuntimeError("checked a unexpected default value.")
else:
if annotation in PlaceAnnotation:
CallParams[name] = PlaceAnnotation[annotation](event_context)
continue
else:
if name not in extra_parameter:
raise RuntimeError(f"checked a unexpected annotation: {annotation}")

executor 中会检查 监听器函数的每个参数的类型定义是否与固有的类型相同,这在一般情况下时可以正常运行的:

# 测试代码
from nakuru import (
    CQHTTP,
    GroupMessage,
)
from nakuru.entities.components import Plain

app = CQHTTP(
    host="127.0.0.1",
    port=8082,
    http_port=5701,
    token="" # 可选,如果配置了 Access-Token
)

@app.receiver("GroupMessage")
async def _(app: CQHTTP, source: GroupMessage):
    # 通过消息链处理
    chain = source.message
    await app.sendGroupMessage(source.group_id, [
        Plain(text="你好"),
    ])

app.run()

image

此情况下 annotation 是类型注解的class 对象,可以通过171行的检查。

添加 from __future__ import annotations

为了避免写类型注解时的循环引用,在测试代码最前方加上from __future__ import annotations后,每个参数的 annotation 会变成 str 类型:
image

此时, executor 方法在 171 行就无法校验通过,而在176行抛出异常抛弃此处事件的处理。但 这种情况下的 监听器函数都是可以正常被调用的。

建议

对 listener 函数的校验更加宽松。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant