相关疑难解决方法(0)

Python:argparse.Namespace对象的Typehints

有没有办法让Python静态分析器(例如在PyCharm,其他IDE中)接受argparse.Namespace对象上的Typehints ?例:

parser = argparse.ArgumentParser()
parser.add_argument('--somearg')
parsed = parser.parse_args(['--somearg','someval'])  # type: argparse.Namespace
the_arg = parsed.somearg  # <- Pycharm complains that parsed object has no attribute 'somearg'
Run Code Online (Sandbox Code Playgroud)

如果我删除内联注释中的类型声明,PyCharm不会抱怨,但它也不会选择无效的属性.例如:

parser = argparse.ArgumentParser()
parser.add_argument('--somearg')
parsed = parser.parse_args(['--somearg','someval'])  # no typehint
the_arg = parsed.somaerg   # <- typo in attribute, but no complaint in PyCharm.  Raises AttributeError when executed.
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?


更新

奥斯汀在下面的回答的启发,我能找到的最简单的解决方案是namedtuples:

from collections import namedtuple
ArgNamespace = namedtuple('ArgNamespace', ['some_arg', 'another_arg'])

parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
parsed …
Run Code Online (Sandbox Code Playgroud)

python type-hinting pycharm argparse python-3.x

27
推荐指数
4
解决办法
3157
查看次数

标签 统计

argparse ×1

pycharm ×1

python ×1

python-3.x ×1

type-hinting ×1