如何使Mypy抱怨将一个Any分配给一个int(第2部分) [英] How to make mypy complain about assigning an Any to an int (part 2)

查看:156
本文介绍了如何使Mypy抱怨将一个Any分配给一个int(第2部分)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这是我的代码库是完全静态类型的(注释),但是在某些时候存在Any类型,例如,因为从JSON字符串中解析了一个值.这是我的最小示例:

My code base is fully statically typed (annotation) but at some points there is the Any type, for example because a value was parsed from a JSON string. Here is my minimal example:

import json
from typing import Any, Dict, Union

def main() -> None:
    data = json.loads('{"value" = "three"}')
    my_int: int = data['value']

if __name__ == "__main__":
    main()

mypy --strict接受此代码.但是,我想自动找到这些地方,以采取适当的安全措施.

mypy --strict accepts this code. However I would like to find these places automatically, to take the appropriate security measures.

是否有可能使mypy抱怨my_int: int = data['value']分配?

Is there any possibility to make mypy complain about the my_int: int = data['value'] assignment?

推荐答案

是-使用"禁止任何系列命令行标志.

Yes -- use the "disallow any" family of command line flags.

在这种情况下,我认为您想专门使用--disallow-any-expr,尽管我建议您也尝试使用其他标志.

In this case, I think you want to use specifically --disallow-any-expr, though I recommend you also experiment with the other flags.

(这些标志不会作为--strict的一部分自动启用,因为它们最终会在某些代码库上引起很多误报,尤其是那些广泛使用无类型库的代码库.)

(These flags are not automatically enabled as a part of --strict because they end up causing a lot of false positives on certain codebases, especially ones that make extensive use of untyped libraries.)

顺便说一句,您可能会发现,启用所有"disallow any"标志最终会带来一些不便,特别是如果您的代码中有特定区域需要进行大量运行时检查时.

As an aside, something you may discover is that enabling all of the "disallow any" flags can end up being a little inconvenient, especially if you have a certain region of your code that needs to do a lot of runtime checks.

为帮助减轻这种情况,我个人想做的是默认情况下启用所有disallow-any标志,但对某些模块禁用其中一些.您可以使用mypy的配置文件来完成此操作.例如,您可以这样做:

To help mitigate this, what I personally like to do is have all of the disallow-any flags enabled by default, but disable a few of them for certain modules. You can do this using mypy's config files. For example, you could do:

[mypy]
# Specify any other global flags you want to customize here
disallow_any_unimported = True
disallow_any_expr = True
disallow_any_decorated = True
disallow_any_explicit = True
disallow_any_generics = True
disallow_subclassing_any = True

[mypy-mymodule.validation]
# Weaken, just for this module
disallow_any_expr = False

然后运行mypy --strict --config my_config.ini mymodule.

除了validation模块中的内容外,几乎所有代码库均不允许使用Any这个配置文件. (然后,我会竭尽全力为该特定模块添加一堆单元测试,以弥补弱化的静态类型检查.)

This config file would disallow the use of Any from almost the entire codebase, except within the validation module. (And then, I'd go out of my way to add a bunch of unit tests for that specific module to make up for the weakened static type checks.)

这篇关于如何使Mypy抱怨将一个Any分配给一个int(第2部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆