Skip to content

Instantly share code, notes, and snippets.

@jackmaney
Last active August 29, 2015 14:27
Show Gist options
  • Save jackmaney/962e1bd65557538254de to your computer and use it in GitHub Desktop.
Save jackmaney/962e1bd65557538254de to your computer and use it in GitHub Desktop.
Delegating Commands in Click
import click
@click.group()
def main():
"""Do things."""
def delegate_command(group, command_name, function, args=None, kwargs=None):
"""
Takes a function that has been decorated with ``click.group`` and delegates a command to it
"""
args = args or ()
kwargs = kwargs or {}
return group.command(command_name)(lambda: function(*args, **kwargs))
def foo(*args, **kwargs):
print("args = {}".format(args))
print("kwargs = {}".format(kwargs))
delegate_command(main, "config", foo, args=(2,3,4), kwargs={"a": 7, "b": "cdefg"})
if __name__ == "__main__":
main()
### Our command has been added:
# $ python click_command_delegation.py --help
# Usage: click_command_delegation.py [OPTIONS] COMMAND [ARGS]...
# Do things.
# Options:
# --help Show this message and exit.
# Commands:
# config
### Everything seems to be in order. It's an actual command with --help built in.
# $ python click_command_delegation.py config --help
# Usage: click_command_delegation.py config [OPTIONS]
# Options:
# --help Show this message and exit.
### And the actual function and arguments (positional and keyword) that we
### passed in seem to actually do their thing!
# $ python click_command_delegation.py config
# args = (2, 3, 4)
# kwargs = {'a': 7, 'b': 'cdefg'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment