Skip to content
Myr

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

1 file+163 added−0 removed

modified:docs/complex.rst+163 added
216 unmodified lines
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:`MultiCommand.list_commands` and :meth:`MultiCommand.get_command`. A custom228:class:`MultiCommand` subclass can implement a lazy loader by storing extra data such229that :meth:`MultiCommand.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.BaseCommand):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 # in foo.py310 import click311312 @click.group(help="foo command for lazy example")313 def cli():314 pass315316 # in bar.py317 import click318 from lazy_group import LazyGroup319320 @click.group(321 cls=LazyGroup,322 lazy_subcommands={"baz": "baz.cli"},323 help="bar command for lazy example",324 )325 def cli():326 pass327328 # in baz.py329 import click330331 @click.group(help="baz command for lazy example")332 def cli():333 pass334335336What triggers Lazy Loading?337```````````````````````````338339There are several events which may trigger lazy loading by running the340:meth:`MultiCommand.get_command` function.341Some are intuititve, and some are less so.342343All cases are described with respect to the above example, assuming the main program344name is ``cli``.3453461. 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.3482. 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``.3513. 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.354355Further Deferring Imports356`````````````````````````357358It is possible to make the process even lazier, but it is generally more difficult the359more you want to defer work.360361For example, subcommands could be represented as a custom :class:`BaseCommand` subclass362which defers importing the command until it is invoked, but which provides363:meth:`BaseCommand.get_short_help_str` in order to support completions and helptext.364More simply, commands can be constructed whose callback functions defer any actual work365until after an import.366367This command definition provides ``foo``, but any of the work associated with importing368the "real" callback function is deferred until invocation time:369370.. click:example::371372 @click.command()373 @click.option("-n", type=int)374 @click.option("-w", type=str)375 def foo(n, w):376 from mylibrary import foo_concrete377378 foo_concrete(n, w)379380Because ``click`` builds helptext and usage info from options, arguments, and command381attributes, it has no awareness that the underlying function is in any way handling a382deferred import. Therefore, all ``click``-provided utilities and functionality will work383as normal on such a command.