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)
有没有什么好的方法可以改善这个问题呢?
您可以使用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 的变量不是必需的,默认为提供的值。
您必须为参数指定默认值以使其可选。