Confused about argparse


April 2019


57 time


I am having some trouble understanding how argparse works and I've combed through the documentation but am still having some difficulty understanding.

def arguments():
parser = argparse.ArgumentParser(description='Test..')
parser.add_argument("-i", "--input-file", required=True, help="input file name")
parser.add_argument("-o", "--output-file", required=True, help="output file name")
parser.add_argument("-r", "--row-limit", required=True, help="row limit to split", type=int)
args = parser.parse_args()

is_valid_file(parser, args.input_file)

is_valid_csv(parser, args.input_file, args.row_limit)

return args.input_file, args.output_file, args.row_limit

def is_valid_file(parser, file_name):
"""Ensure that the input_file exists"""
if not os.path.exists(file_name):
    parser.error("The file {} does not exist".format(file_name))

def is_valid_csv(parser, file_name, row_limit):
Ensure that the # of rows in the input_file
is greater than the row_limit.
row_count = 0
for row in csv.reader(open(file_name)):
    row_count += 1
if row_limit > row_count:
    parser.error("More rows than actual rows in the file")

The code above works fine, but once I remove "--row-limit" on line 5, I get a

Traceback (most recent call last):
 File ".\", line 95, in <module>
  arguments = arguments()
 File ".\", line 33, in arguments
  is_valid_csv(parser, args.input_file, args.row_limit)
AttributeError: 'Namespace' object has no attribute 'row_limit'

Why does removing the "--row-limit" present me with this error?

1 answers


args = parser.parse_args() actually adds an attribute to the namespace args for each parser.add_argument call. The name of the attribute is generated from your argument name, here --row-limit is transformed to row_limit because you can't have dashes in variable names. See the argparse documentation for details.

So when you call parser.add_argument(..., "--row-limit", ...), it creates args.row_limit once you invoke parse_args(). As Amadan mentioned, you use args.row_limit later on in your code. But if you remove the --row-limit argument from the parser, the attribute row_limit won't exist in args.