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

rka*_*moi 7 python pylint type-hinting 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)
Run Code Online (Sandbox Code Playgroud)

有没有什么好的方法可以改善这个问题呢?

PIG*_*208 3

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

这给你:

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"
Run Code Online (Sandbox Code Playgroud)

对于必需的参数,请注意:

定义为 name: type 的变量是必需参数,而定义为 name: type = value 的变量不是必需的,默认为提供的值。

您必须为参数指定默认值以使其可选。

  • 如果还有其他侵入性较小的方法,我会洗耳恭听(作为图书馆维护者)。这不是普通的“argparse”,它是与之同等的第三方依赖项。另一个问题是它不仅仅是一个 mypy 插件(这不能是开发依赖项),它是一个运行时包,具有所有成本、潜在的错误等。对我来说,这否定了标准库 argparse 和注释的好处。 (2认同)