Skip to content
Myr

complex.rst

This file

Path

docs/complex.rst

389 lines · 13.2 KiB

Last changed by

deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc

History of this file

Take it

1.. _complex-guide:23Complex Applications4====================56.. currentmodule:: click78Click is designed to assist with the creation of complex and simple CLI tools9alike.  However, the power of its design is the ability to arbitrarily nest10systems together.  For instance, if you have ever used Django, you will11have realized that it provides a command line utility, but so does Celery.12When using Celery with Django, there are two tools that need to interact with13each other and be cross-configured.1415In a theoretical world of two separate Click command line utilities, they16could solve this problem by nesting one inside the other.  For instance, the17web framework could also load the commands for the message queue framework.1819Basic Concepts20--------------2122To understand how this works, you need to understand two concepts: contexts23and the calling convention.2425Contexts26````````2728Whenever a Click command is executed, a :class:`Context` object is created29which holds state for this particular invocation.  It remembers parsed30parameters, what command created it, which resources need to be cleaned up31at the end of the function, and so forth.  It can also optionally hold an32application-defined object.3334Context objects build a linked list until they hit the top one.  Each context35is linked to a parent context.  This allows a command to work below36another command and store its own information there without having to be37afraid of altering up the state of the parent command.3839Because the parent data is available, however, it is possible to navigate to40it if needed.4142Most of the time, you do not see the context object, but when writing more43complex applications it comes in handy.  This brings us to the next point.4445Calling Convention46``````````````````4748When a Click command callback is executed, it's passed all the non-hidden49parameters as keyword arguments.  Notably absent is the context.  However,50a callback can opt into being passed to the context object by marking itself51with :func:`pass_context`.5253So how do you invoke a command callback if you don't know if it should54receive the context or not?  The answer is that the context itself55provides a helper function (:meth:`Context.invoke`) which can do this for56you.  It accepts the callback as first argument and then invokes the57function correctly.5859Building a Git Clone60--------------------6162In this example, we want to build a command line tool that resembles a63version control system.  Systems like Git usually provide one64over-arching command that already accepts some parameters and65configuration, and then have extra subcommands that do other things.6667The Root Command68````````````````6970At the top level, we need a group that can hold all our commands.  In this71case, we use the basic :func:`click.group` which allows us to register72other Click commands below it.7374For this command, we also want to accept some parameters that configure the75state of our tool:7677.. click:example::7879    import os80    import click818283    class Repo(object):84        def __init__(self, home=None, debug=False):85            self.home = os.path.abspath(home or '.')86            self.debug = debug878889    @click.group()90    @click.option('--repo-home', envvar='REPO_HOME', default='.repo')91    @click.option('--debug/--no-debug', default=False,92                  envvar='REPO_DEBUG')93    @click.pass_context94    def cli(ctx, repo_home, debug):95        ctx.obj = Repo(repo_home, debug)969798Let's understand what this does.  We create a group command which can99have subcommands.  When it is invoked, it will create an instance of a100``Repo`` class.  This holds the state for our command line tool.  In this101case, it just remembers some parameters, but at this point it could also102start loading configuration files and so on.103104This state object is then remembered by the context as :attr:`~Context.obj`.105This is a special attribute where commands are supposed to remember what106they need to pass on to their children.107108In order for this to work, we need to mark our function with109:func:`pass_context`, because otherwise, the context object would be110entirely hidden from us.111112The First Child Command113```````````````````````114115Let's add our first child command to it, the clone command:116117.. click:example::118119    @cli.command()120    @click.argument('src')121    @click.argument('dest', required=False)122    def clone(src, dest):123        pass124125So now we have a clone command, but how do we get access to the repo?  As126you can imagine, one way is to use the :func:`pass_context` function which127again will make our callback also get the context passed on which we128memorized the repo.  However, there is a second version of this decorator129called :func:`pass_obj` which will just pass the stored object, (in our case130the repo):131132.. click:example::133134    @cli.command()135    @click.argument('src')136    @click.argument('dest', required=False)137    @click.pass_obj138    def clone(repo, src, dest):139        pass140141Interleaved Commands142````````````````````143144While not relevant for the particular program we want to build, there is145also quite good support for interleaving systems.  Imagine for instance that146there was a super cool plugin for our version control system that needed a147lot of configuration and wanted to store its own configuration as148:attr:`~Context.obj`.  If we would then attach another command below that,149we would all of a sudden get the plugin configuration instead of our repo150object.151152One obvious way to remedy this is to store a reference to the repo in the153plugin, but then a command needs to be aware that it's attached below such a154plugin.155156There is a much better system that can be built by taking advantage of the157linked nature of contexts.  We know that the plugin context is linked to the158context that created our repo.  Because of that, we can start a search for159the last level where the object stored by the context was a repo.160161Built-in support for this is provided by the :func:`make_pass_decorator`162factory, which will create decorators for us that find objects (it163internally calls into :meth:`Context.find_object`).  In our case, we164know that we want to find the closest ``Repo`` object, so let's make a165decorator for this:166167.. click:example::168169    pass_repo = click.make_pass_decorator(Repo)170171If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a172repo instead of something else:173174.. click:example::175176    @cli.command()177    @click.argument('src')178    @click.argument('dest', required=False)179    @pass_repo180    def clone(repo, src, dest):181        pass182183Ensuring Object Creation184````````````````````````185186The above example only works if there was an outer command that created a187``Repo`` object and stored it in the context.  For some more advanced use188cases, this might become a problem.  The default behavior of189:func:`make_pass_decorator` is to call :meth:`Context.find_object`190which will find the object.  If it can't find the object,191:meth:`make_pass_decorator` will raise an error.192The alternative behavior is to use :meth:`Context.ensure_object`193which will find the object, and if it cannot find it, will create one and194store it in the innermost context.  This behavior can also be enabled for195:func:`make_pass_decorator` by passing ``ensure=True``:196197.. click:example::198199    pass_repo = click.make_pass_decorator(Repo, ensure=True)200201In this case, the innermost context gets an object created if it is202missing.  This might replace objects being placed there earlier.  In this203case, the command stays executable, even if the outer command does not run.204For this to work, the object type needs to have a constructor that accepts205no arguments.206207As such it runs standalone:208209.. click:example::210211    @click.command()212    @pass_repo213    def cp(repo):214        click.echo(isinstance(repo, Repo))215216As you can see:217218.. click:run::219220    invoke(cp, [])221222Lazily Loading Subcommands223--------------------------224225Large CLIs and CLIs with slow imports may benefit from deferring the loading of226subcommands. The interfaces which support this mode of use are227:meth:`Group.list_commands` and :meth:`Group.get_command`. A custom228:class:`Group` subclass can implement a lazy loader by storing extra data such229that :meth:`Group.get_command` is responsible for running imports.230231Since the primary case for this is a :class:`Group` which loads its subcommands lazily,232the following example shows a lazy-group implementation.233234.. warning::235236   Lazy loading of python code can result in hard to track down bugs, circular imports237   in order-dependent codebases, and other surprising behaviors. It is recommended that238   this technique only be used in concert with testing which will at least run the239   ``--help`` on each subcommand. That will guarantee that each subcommand can be loaded240   successfully.241242Defining the Lazy Group243```````````````````````244245The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which246stores a mapping from subcommand names to the information for importing them.247248.. code-block:: python249250    # in lazy_group.py251    import importlib252    import click253254    class LazyGroup(click.Group):255        def __init__(self, *args, lazy_subcommands=None, **kwargs):256            super().__init__(*args, **kwargs)257            # lazy_subcommands is a map of the form:258            #259            #   {command-name} -> {module-name}.{command-object-name}260            #261            self.lazy_subcommands = lazy_subcommands or {}262263        def list_commands(self, ctx):264            base = super().list_commands(ctx)265            lazy = sorted(self.lazy_subcommands.keys())266            return base + lazy267268        def get_command(self, ctx, cmd_name):269            if cmd_name in self.lazy_subcommands:270                return self._lazy_load(cmd_name)271            return super().get_command(ctx, cmd_name)272273        def _lazy_load(self, cmd_name):274            # lazily loading a command, first get the module name and attribute name275            import_path = self.lazy_subcommands[cmd_name]276            modname, cmd_object_name = import_path.rsplit(".", 1)277            # do the import278            mod = importlib.import_module(modname)279            # get the Command object from that module280            cmd_object = getattr(mod, cmd_object_name)281            # check the result to make debugging easier282            if not isinstance(cmd_object, click.Command):283                raise ValueError(284                    f"Lazy loading of {import_path} failed by returning "285                    "a non-command object"286                )287            return cmd_object288289Using LazyGroup To Define a CLI290```````````````````````````````291292With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its293subcommands like so:294295.. code-block:: python296297    # in main.py298    import click299    from lazy_group import LazyGroup300301    @click.group(302        cls=LazyGroup,303        lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"},304        help="main CLI command for lazy example",305    )306    def cli():307        pass308309.. code-block:: python310311    # in foo.py312    import click313314    @click.group(help="foo command for lazy example")315    def cli():316        pass317318.. code-block:: python319320    # in bar.py321    import click322    from lazy_group import LazyGroup323324    @click.group(325        cls=LazyGroup,326        lazy_subcommands={"baz": "baz.cli"},327        help="bar command for lazy example",328    )329    def cli():330        pass331332.. code-block:: python333334    # in baz.py335    import click336337    @click.group(help="baz command for lazy example")338    def cli():339        pass340341342What triggers Lazy Loading?343```````````````````````````344345There are several events which may trigger lazy loading by running the346:meth:`Group.get_command` function.347Some are intuititve, and some are less so.348349All cases are described with respect to the above example, assuming the main program350name is ``cli``.3513521. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``,353   and then resolve ``baz``. Each subcommand resolution step does a lazy load.3542. Helptext rendering. In order to get the short help description of subcommands,355   ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load356   ``baz``.3573. Shell completion. In order to get the subcommands of a lazy command, ``cli <TAB>``358   will need to resolve the subcommands of ``cli``. This process will trigger the lazy359   loads.360361Further Deferring Imports362`````````````````````````363364It is possible to make the process even lazier, but it is generally more difficult the365more you want to defer work.366367For example, subcommands could be represented as a custom :class:`Command` subclass368which defers importing the command until it is invoked, but which provides369:meth:`Command.get_short_help_str` in order to support completions and helptext.370More simply, commands can be constructed whose callback functions defer any actual work371until after an import.372373This command definition provides ``foo``, but any of the work associated with importing374the "real" callback function is deferred until invocation time:375376.. click:example::377378    @click.command()379    @click.option("-n", type=int)380    @click.option("-w", type=str)381    def foo(n, w):382        from mylibrary import foo_concrete383384        foo_concrete(n, w)385386Because Click builds helptext and usage info from options, arguments, and command387attributes, it has no awareness that the underlying function is in any way handling a388deferred import. Therefore, all Click-provided utilities and functionality will work389as normal on such a command.