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