Python: Typehints for argparse.Namespace objects

前端 未结 3 1965
悲哀的现实
悲哀的现实 2020-12-14 06:39

Is there a way to have Python static analyzers (e.g. in PyCharm, other IDEs) pick up on Typehints on argparse.Namespace objects? Example:

parse         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 06:55

    Consider defining an extension class to argparse.Namespace that provides the type hints you want:

    class MyProgramArgs(argparse.Namespace):
        def __init__():
            self.somearg = 'defaultval' # type: str
    

    Then use namespace= to pass that to parse_args:

    def process_argv():
        parser = argparse.ArgumentParser()
        parser.add_argument('--somearg')
        nsp = MyProgramArgs()
        parsed = parser.parse_args(['--somearg','someval'], namespace=nsp)  # type: MyProgramArgs
        the_arg = parsed.somearg  # <- Pycharm should not complain
    

提交回复
热议问题