Home > Software design >  How to see the attributes of argparse.NameSpace Python object?
How to see the attributes of argparse.NameSpace Python object?

Time:11-17

For a project involving multiple scripts (data processing, model tuning, model training, testing, etc.) I may keep all my <class 'argparse.ArgumentParser'> objects as the return value of functions for each script task in a module I name cli.py. However, in the calling script itself (__main__), after calling args = parser.parse_args(), if I type args. in VS Code I get no suggested attributes that are specific to that object. How can I get suggested attributes of argparse.NameSpace objects in VS Code?

E.g.,

"""Module for command line interface for different scripts."""
import argparse
def some_task_parser(description: str) -> argparse.ArgumentParser:
  parser = argparse.ArgumentParser(description=description)
  parser.add_argument('some_arg')
  return parser

then

"""Script for executing some task."""
from cli import some_task_parser
if __name__ == '__main__':
  parser = some_task_parser('arbitrary task')
  args = parser.parse_args()
  print(args.)  # I WANT SUGGESTED ATTRIBUTES (SUCH AS args.some_arg) TO POP UP!!

CodePudding user response:

I don't know about VSCode, in an ipython session, the tab complete does show the available attributes of Namespace. argparse.Namespace is a relatively simple object class. What you want, I think, are just the attributes of this object.

In [238]: args = argparse.Namespace(test='one', foo='three', bar=3)
In [239]: args
Out[239]: Namespace(bar=3, foo='three', test='one')
In [240]: args.
                bar      test    
                foo      args.txt

But those attributes will not be available during development. They are put there by the parsing action, at run time. They cannot be reliably deduced from the parser setup. Certainly argparse does not provide such a help.

I often recommend that developers include a

print(args)

during the debugging phase, so they get a clear idea of what the parser does.

  • Related