Constantinos N
Constantinos N

Reputation: 263

Default Values don't work with Positional and Optional arguments present

My code (train.py):

parser = argparse.ArgumentParser()

    parser.add_argument('data_dir')
    parser.add_argument('--save_dir', type = str, default = 'save_directory', help = 'Save checkpoint directory')
    parser.add_argument('--arch', type = str, default = 'VGG', help = 'Select architecture. Choose VGG or AlexNet')
    parser.add_argument('--learning_rate', type = float, default = '0.001', help = 'Select the model learning rate')
    parser.add_argument('--hidden_units', type = int, default = '1024', help = 'Select the model hidden units')
    parser.add_argument('--epochs', type = int, default = '2', help = 'Select the number of epochs')
    parser.add_argument('--gpu', type = str, default = 'gpu', help = 'Select the device type. CPU or GPU.')

    return parser.parse_args()

When I try to run

python train.py data_dir --arch

I get

train.py: error: argument --arch: expected one argument

Why do my default values not work?

Upvotes: 0

Views: 91

Answers (2)

gmds
gmds

Reputation: 19885

There are three ways you can pass the '--arch' argument:

  1. Not at all, which will use the value from default.
  2. With '--arch' alone, which will use the value from const. Since const was originally not specified, this case defaulted to None, making it the same as the first case.
  3. With '--arch <value>', which will use <value>.

Therefore, you need to specify that the flag takes a further optional argument with nargs='?', and the value of const:

parser.add_argument('--arch',
                    nargs='?', 
                    type=str, 
                    const='VGG',
                    default='VGG',
                    help='Select architecture. Choose VGG or AlexNet')

You may also wish to note that you can pass choices=['VGG', 'AlexNet'] to constrain the available choices (an error will be raised if the argument is not in choices).

Upvotes: 2

rdas
rdas

Reputation: 21275

Default values are substituted when the corresponding argument is not present.

You have defined --arch as "an optional argument which takes string values, and if not present it should be VGG"

If you pass --arch it should have a string value. If you don't pass --arch it will be VGG.

You have tried something in-between. That's an error case.

Upvotes: 2

Related Questions