click-contrib/click-option-group

Consuming groups in function arguments

LecrisUT opened this issue · 2 comments

This might be a bit tricky to implement, but would be nice to have:

@click.command
@optgroup.group('My group', 'my_group')
@optgroup.option('--foo')
@optgroup.option('--bar')
@click.option('--click-option')
def my_func(my_group,click_option):
  pass

I.e. access the whole group as a dict my_group. A hacky workaround would be:

def _my_group(func):
    """Select group options"""

    @optgroup.group('My group'')
    @optgroup.option('--foo')
    @optgroup.option('--bar')
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        my_group = {
            opt: kwargs.pop(opt)
            for opt in ('foo', 'bar')
        }
        return func(*args, my_group=my_group, **kwargs)

    return wrapper

@click.command
@_my_group
@click.option('--click-option')
def my_func(my_group,click_option):
  pass

Probably this can be adapted for proper implementation

I am looking for this too, tried to see if I could do something with handle_parse_result and set the result on the context, but your hack seems better

espdev commented

Hello guys,
I don't mind. PRs are welcome :)