Search code examples
pythonargparse

AttributeError: 'Namespace' object has no attribute 'myFile'


I am relatively new to python and trying to understand network code written in python. I however encounter this problem when I run the code. The relevant part of the code is as shown below:

if __name__ == "__main__":
  parser = argparse.ArgumentParser(description="write data file for optimization model")
  parser.add_argument("--graph", metavar="myFile", default=" ", type=str, help="graphml file")
  parser.add_argument("--budget", type=int, default=0, help='budget')
  parser.add_argument("--nsamples", type=int, default=0,help='number of random samples')
  args = parser.parse_args()
  
  budget = getattr(args, 'budget')
  graphFile = getattr(args, 'myFile')
  nsamples = getattr(args, 'nsamples')
  roadSegGraph = nx.read_graphml(graphFile)

The error is

C:\Users\aduam\anaconda3\python.exe "C:/Users/aduam/Downloads/smartcities-master (2)/smartcities-master/Models/real_soc_function/write_data.py" Traceback (most recent call last): File "C:\Users\aduam\Downloads\smartcities-master (2)\smartcities-master\Models\real_soc_function\write_data.py", line 344, in graphFile = getattr(args, 'myFile') AttributeError: 'Namespace' object has no attribute 'myFile'


Solution

  • metavar modifies the name of the argument in the outputted help/usage message only, as per the docs:

    Note that metavar only changes the displayed name - the name of the attribute on the parse_args() object is still determined by the dest value.

    You are looking for dest.

    Also, i'm not sure why you are using getattr.

    budget = getattr(args, 'budget')
    graphFile = getattr(args, 'myFile')
    nsamples = getattr(args, 'nsamples')
    

    can and should just be

    budget = args.budget
    graphFile = args.myFile
    samples = args.nsamples