Mypy调用的自定义名称空间

发布于 2025-01-19 02:31:27 字数 135 浏览 2 评论 0原文

我想使用 mypy 对 python 脚本进行类型检查。该脚本依赖于调用脚本时通过 exec 设置的全局变量。

有没有一种方法可以使用类似于 exec 的变量字典来调用 mypy,以便可以对我的脚本进行类型检查?如果这不可能,有哪些替代方法?

I want to use mypy to typecheck a python script. This script depends on global variables that are set via exec when the script is called.

Is there a way to invoke mypy with a dictionary of variables similar to exec so my script can be type checked? If this is not possible what are the alternative approaches?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风启觞 2025-01-26 02:31:27

您可以显式告诉 mypy 源代码中存在哪些变量:

MY_EXTRA_VAR: int

print("result", MY_EXTRA_VAR + 10)

现在 mypy 不会抱怨。但是您也可以像这样摆脱调用魔法:

def run(my_extra_var: int):
    print("result", my_extra_var + 10)

然后您必须更改调用脚本以导入模块(可能是动态的)并运行 run 函数。

You can explicitly tell mypy which variables exist in the source code:

MY_EXTRA_VAR: int

print("result", MY_EXTRA_VAR + 10)

Now mypy won't complain. But you can also get rid of the calling magic like this:

def run(my_extra_var: int):
    print("result", my_extra_var + 10)

Then you have to change your calling script to import the module (maybe dynamically) and run the run function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文