为 argparse 参数提供类型提示比自定义命名空间更好的选择

问题描述 投票:0回答:1

我正在尝试使用 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

正如here提到的,我还尝试提供自定义名称空间。这将
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)
python argparse type-hinting mypy
1个回答
0
投票

您检查过 2022 年的 this 答案吗?我相信它符合您的所有标准:

© www.soinside.com 2019 - 2024. All rights reserved.