python - 如何为 argparse 参数提供类型提示?

标签 python type-hinting pylint mypy python-typing

我想通过 [PyFlakes, Pylint] 和 mypy 获得适当的 linting 和类型提示。
例如,在下面的代码中,我们无法获取最后一行的类型错误。
我们甚至不知道 float_input存在。

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--float_input', type=float)
args = parser.parse_args()


def int_sum(a: int, b: int):
    return a + b

c = int_sum(args.float_input, args.float_input)
有什么好的方法可以改善这种情况吗?

最佳答案

您可以使用 typed-argument-parser为您的参数提供类型提示。您可以以类型安全的方式定义参数。

from typing import Optional
from tap import Tap

class FooArgumentParser(Tap):
    float_input: Optional[float] = None

args = FooArgumentParser().parse_args()


def int_sum(a: int, b: int):
    return a + b


c = int_sum(args.float_input, args.float_input)
c = int_sum(args.foo, args.bar)
这给了你:
foo.py:13:13: error: Argument 1 to "int_sum" has incompatible type "Optional[float]"; expected "int"
foo.py:13:31: error: Argument 2 to "int_sum" has incompatible type "Optional[float]"; expected "int"
foo.py:14:13: error: "FooArgumentParser" has no attribute "foo"
foo.py:14:23: error: "FooArgumentParser" has no attribute "bar"
对于必需的参数,请注意:

Variables defined as name: type are required arguments while variables defined as name: type = value are not required and default to the provided value.


您必须为参数提供默认值以使其可选。

关于python - 如何为 argparse 参数提供类型提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69553159/

相关文章:

python - 方法的装饰器参数不能是基于类的静态成员的列表理解

python - 如何将 pylint 检查仅限于当前存储库定义的对象?

Python:兼容性需要未使用的参数。如何避免Pylint提示它

python - 发送元组列表作为电子邮件正文和原始电子邮件消息

python - 从 python 更改 C 变量?

没有Python 3类型提示?

php - PHP 代码中莫名其妙的类型提示

Python - 无论发生什么异常,我如何让程序永远运行?

python - 如何使用 Keras 处理 CNN 中可变大小的输入?

symfony - 如何使用 phpstorm 和 symfony2 插件获得容器的自动完成功能?