Extend Complex Application docs with Lazy Loading (#2348)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 6ae9428, 919d76a · Browse files · 1 file·+163 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+163 added−0 removed
- other:+163 added−0 removed
Provenance
- Commit
5bdd954- Tree
13ee2da- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
6ae9428- Parent 2
919d76a
1 file changed+163 added−0 removed
modified:docs/complex.rst+163 added
216 unmodified lines217 218 .. click:run::219 220 invoke(cp, [])221+222+Lazily Loading Subcommands223+--------------------------224+225+Large CLIs and CLIs with slow imports may benefit from deferring the loading of226+subcommands. The interfaces which support this mode of use are227+:meth:`MultiCommand.list_commands` and :meth:`MultiCommand.get_command`. A custom228+:class:`MultiCommand` subclass can implement a lazy loader by storing extra data such229+that :meth:`MultiCommand.get_command` is responsible for running imports.230+231+Since the primary case for this is a :class:`Group` which loads its subcommands lazily,232+the following example shows a lazy-group implementation.233+234+.. warning::235+236+ 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.241+242+Defining the Lazy Group243+```````````````````````244+245+The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which246+stores a mapping from subcommand names to the information for importing them.247+248+.. code-block:: python249+250+ # in lazy_group.py251+ import importlib252+ import click253+254+ 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 {}262+263+ def list_commands(self, ctx):264+ base = super().list_commands(ctx)265+ lazy = sorted(self.lazy_subcommands.keys())266+ return base + lazy267+268+ 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)272+273+ 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.BaseCommand):283+ raise ValueError(284+ f"Lazy loading of {import_path} failed by returning "285+ "a non-command object"286+ )287+ return cmd_object288+289+Using LazyGroup To Define a CLI290+```````````````````````````````291+292+With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its293+subcommands like so:294+295+.. code-block:: python296+297+ # in main.py298+ import click299+ from lazy_group import LazyGroup300+301+ @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+ pass308+309+ # in foo.py310+ import click311+312+ @click.group(help="foo command for lazy example")313+ def cli():314+ pass315+316+ # in bar.py317+ import click318+ from lazy_group import LazyGroup319+320+ @click.group(321+ cls=LazyGroup,322+ lazy_subcommands={"baz": "baz.cli"},323+ help="bar command for lazy example",324+ )325+ def cli():326+ pass327+328+ # in baz.py329+ import click330+331+ @click.group(help="baz command for lazy example")332+ def cli():333+ pass334+335+336+What triggers Lazy Loading?337+```````````````````````````338+339+There are several events which may trigger lazy loading by running the340+:meth:`MultiCommand.get_command` function.341+Some are intuititve, and some are less so.342+343+All cases are described with respect to the above example, assuming the main program344+name is ``cli``.345+346+1. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``,347+ and then resolve ``baz``. Each subcommand resolution step does a lazy load.348+2. Helptext rendering. In order to get the short help description of subcommands,349+ ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load350+ ``baz``.351+3. Shell completion. In order to get the subcommands of a lazy command, ``cli <TAB>``352+ will need to resolve the subcommands of ``cli``. This process will trigger the lazy353+ loads.354+355+Further Deferring Imports356+`````````````````````````357+358+It is possible to make the process even lazier, but it is generally more difficult the359+more you want to defer work.360+361+For example, subcommands could be represented as a custom :class:`BaseCommand` subclass362+which defers importing the command until it is invoked, but which provides363+:meth:`BaseCommand.get_short_help_str` in order to support completions and helptext.364+More simply, commands can be constructed whose callback functions defer any actual work365+until after an import.366+367+This command definition provides ``foo``, but any of the work associated with importing368+the "real" callback function is deferred until invocation time:369+370+.. click:example::371+372+ @click.command()373+ @click.option("-n", type=int)374+ @click.option("-w", type=str)375+ def foo(n, w):376+ from mylibrary import foo_concrete377+378+ foo_concrete(n, w)379+380+Because ``click`` builds helptext and usage info from options, arguments, and command381+attributes, it has no awareness that the underlying function is in any way handling a382+deferred import. Therefore, all ``click``-provided utilities and functionality will work383+as normal on such a command.