Fred Zimmerman
Fred Zimmerman

Reputation: 1238

how can argparse set default value of optional parameter to null or empty?

I am using python argparse to read an optional parameter that defines an "exemplar file" that users sometimes provide via the command line. I want the default value of the variable to be empty, that is no file found.

parser.add_argument("--exemplar_file", help = "file to inspire book", default = '')

Will this do it?

Upvotes: 9

Views: 20179

Answers (2)

hpaulj
hpaulj

Reputation: 231385

The default default is None (for the default store action). A nice thing about is that your user can't provide that value (there's no string that converts to None). It is easy to test

 if args.examplar_file is None:
     # do your thing
     # args.exampler_file = 'the real default'
 else:
     # use args.examplar_file

But default='' is fine. Try it.

Upvotes: 5

user94559
user94559

Reputation: 60143

Just don't set a default:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--exemplar_file', help='file to inspire book')

args = parser.parse_args()

print(args.exemplar_file)

# Output:
# None

Upvotes: 12

Related Questions