Joan Pérez
Joan Pérez

Reputation: 123

Replace empty strings on argparse to None

I am using groovy to call a python class, I am defaulting to None the empty arguments, but I am finding lots of problems to default to None null or empty strings ('') also.

I hope there would be something in argparse to check if the argument is '' and change it to None in that case so further in the code I don't have to check for None and for '' just check if is not None.

Upvotes: 10

Views: 9237

Answers (2)

BoarGules
BoarGules

Reputation: 16952

Specify the command line argument as having type str with default None, for example:

parser.add_argument('-j', '--jfile', default=None, type=str)

Then if the user omits -j entirely then you will get None back. But if the user puts -j on the command line with nothing after it, they will get the error argument -j/--jfile: expected one argument and they will have to supply a string value to get past this. So you should always get either None or a non-empty string.

Upvotes: 7

user2201041
user2201041

Reputation:

The type argument of ArgumentParser.add_argument() is a function that "allows any necessary type-checking and type conversions to be performed." You can abuse this:

import argparse

def nullable_string(val):
    if not val:
        return None
    return val

parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=nullable_string)
print(parser.parse_args(['--foo', ''])

Output:

Namespace(foo=None)

Upvotes: 15

Related Questions