Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python click pass unspecified number of kwargs [duplicate]

Recently discovered click and I would like to pass an unspecified number of kwargs to a click command. Currently this is my command:

@click.command()
@click.argument('tgt')
@click.argument('fun')
@click.argument('args', nargs=-1)
def runner(tgt, fun, args):
    req = pyaml.p(meh.PostAdapter(tgt, fun, *args))
    click.echo(req)

However when using nargs anything more than 1 is passed as a tuple ([docs][1]) and I cannot type=dict that unfortunately.

But it should be possible to do something like this:

command positional1 positional2 foo='bar' baz='qux' xxx='yyy'

Thanks in advance for any help or suggestions, in the meantime I will keep chipping away at this myself.

like image 922
beardedeagle Avatar asked Apr 09 '16 06:04

beardedeagle


People also ask

How do you specify Kwargs Python?

Python **kwargs In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk ** .

Can you have Kwargs without args?

First of all, let me tell you that it is not necessary to write *args or **kwargs. Only the * (asterisk) is necessary. You could have also written *var and **vars. Writing *args and **kwargs is just a convention.

Can you pass Kwargs as a dictionary?

“ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.

What is the difference between args and Kwargs?

*args specifies the number of non-keyworded arguments that can be passed and the operations that can be performed on the function in Python whereas **kwargs is a variable number of keyworded arguments that can be passed to a function that can perform dictionary operations.


1 Answers

Using the link that @rmn provided, I rewrote my click command as follows:

@click.command(context_settings=dict(
    ignore_unknown_options=True,
    allow_extra_args=True,
))
@click.pass_context
def runner(ctx, tgt, fun):
    d = dict()
    for item in ctx.args:
        d.update([item.split('=')])
    req = pyaml.p(meh.PostAdapter(tgt, fun, d))
    click.echo(req)

Which allows me to issue the following command properly:

mycmd tgt fun foo='bar' baz='qux' xxx='yyy'

like image 164
beardedeagle Avatar answered Sep 18 '22 09:09

beardedeagle