Click: Optional arguments

Created on 25 May 2014  路  6Comments  路  Source: pallets/click

Are optional arguments currently possible with click?

For example...

$ greet
hello all
$ greet john
hello john
$ greet john sally
hello john and sally

Most helpful comment

Yes. Set required to false.

All 6 comments

Yes. Set required to false.

Answered my own question!
Seems you beat me too comment mitsuhiko :)

Just saw the required flag in http://click.pocoo.org/api/#parameters

If anyone else stumbles across this, as a quick ref, it's a simple as...

@cli.command()
@click.argument('names', nargs=-1, required=False)
def greet(names):
    if len(names) == 0:
        print "hello all"
    else:
       print "hello {}".format(" and ".join(names))

JFTR: if nargs is -1 then the argument becomes implicitly "non required". An empty sequence still works.

I think the documentation could make this flag more obvious, by putting a section on the Arguments page.

I landed here looking for a way of specifying multiple optional arguments. Based on the examples above, I did:

@click.command()
@click.argument('size', required=False)
@click.argument('flavour', required=False)
def order_pizza(size, flavour):
    print "Ordering {} ({})".format(size, flavour)

This gives you two positional arguments, both of which are optional.

This helped me today. :)

Was this page helpful?
0 / 5 - 0 ratings