6

I'm trying to write a management command in django. According to the documentation default is set to False. I would assume that the default is the default value of the argument that is being passed. Make django custom management command argument "Not Required"

What's the benefit of stating that deafult=False

class Command(BaseCommand):
    help = "helps in doing stuff"

    def add_arguments(self, parser):
        parser.add_argument(
            'name', type=str, default=False,
            help="The name of the folder to be created")

    def handle(self, *args, **options):
        pass
Alasdair
  • 298,606
  • 55
  • 578
  • 516
acquayefrank
  • 474
  • 5
  • 21
  • what do you mean by "according to the documentation default is set to false"? You can set default to whatever you want. – Kos Oct 24 '17 at 10:33

2 Answers2

14

The first example in the docs you link to is for an optional named argument --delete. Setting action='store_true' means that if you include --delete in the command, then args.delete will be set to True, and if --delete is not included in the command then it will default=False.

In this case, setting default=False isn't actually required, because that's the behaviour of action='store_true'. The advantage of explicitly setting default=False is that the behaviour is clear without needing to look up the argparse docs.

    parser.add_argument(
        '--delete',
        action='store_true',
        dest='delete',
        default=False,
        help='Delete poll instead of closing it',
    )

Your example does not make sense, because name is not an optional argument.

parser.add_argument(
    'name', type=str, default=False,
    help="The name of the folder to be created")

If you try this example then you will get an error like too few arguments.

parser.add_argument(
    'name', type=str, default=False
    help="The name of the folder to be created")

You need to set nargs='?' if you want he name argument to be optional. In this case, your default will be used. If you didn't set it, then it will default to None

parser.add_argument(
    'name', type=str, nargs='?', default=False,
    help="The name of the folder to be created")

Note that if your argument is the 'name of the folder to be created', it might not make sense to set the default to False. It seems like either the argument should be required (in which case no default is needed) or the default should be a string e.g. /path/to/folder/.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
1

The value of default is what the argument will be set to if it's not passed in to the command.

In your case, if you call your command and don't provide a name through the CLI, options['name'] will be set to False (your default value).

TeaPow
  • 687
  • 8
  • 17
  • For the example above, `name` is a required argument, so the default won't be used. Instead, you'll get `error: too few arguments`. – Alasdair Oct 24 '17 at 10:46