我正在尝试使用 mypy 来检查我的程序。该程序使用 argparse 来解析命令行参数。我想为命令行参数添加类型提示。
import argparse
import typing
# define example types and a function that uses them
Seconds = typing.NewType("Seconds", float)
Minutes = typing.NewType("Minutes", float)
def sec_to_min(s: Seconds) -> Minutes:
return Minutes(s / 60)
# specify arguments and parse them
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--time", default=1., type=float,
help="time in seconds")
args = parser.parse_args()
try:
# mypy reveals type Any
reveal_type(args.time)
except NameError:
pass
# (1) passes type check
seconds: Seconds = args.time
# (2) passes type check
sec_to_min(args.time)
我希望 mypy 将
args.time
识别为 Seconds
。当前代码应该将 args.time
识别为浮动并抱怨,因为将浮动传递给 sec_to_min
也会抱怨。
我尝试将
type
的 add_argument
参数更改为 type=lambda x: Seconds(float(x))
。这没有效果,mypy 仍然将 args.time
识别为 any
。args.time
的显示类型更改为 Seconds
。我想避免这种情况,因为我必须重复每个参数的名称,并且 add_argument
的默认值被自定义命名空间覆盖。
class TypedNameSpace(argparse.Namespace):
def __init__(self, *args, **kwargs):
self.time: Seconds = Seconds(0.)
super(TypedNameSpace, self).__init__(*args, **kwargs)
您检查过 2022 年的 this 答案吗?我相信它符合您的所有标准: