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

How to provide type hints for argparse arguments?

我想通过 [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.

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