Skip to content
Myr

Extend Complex Application docs with Lazy Loading

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Resolves #945 The goal of this example is to show how one might subclass Group, overriding `get_command` and `list_commands` with some importlib usage and a dict, and produce a viable lazy-loading solution. One significant benefit of offering an example is that it provides space to explain how and when `get_command` is invoked. i.e. Users might be surprised to realize that subcommands are resolved during completion scenarios. At the risk of diverging a small amount into what some would consider "general deferred import semantics in python", the section closes out with an example of a `click.command` decorated function which contains a deferred import. For codebases which have significant at-import-time work (e.g. importing `requests` or `urllib3`), this strategy is probably *more* useful than lazy loading of subcommands. Other variations on this same solution are possible, e.g. using `importlib.load_module(module_name, self.callback.__module__)` to handle imports relative to the definition of the callback function. However, any further work in this space is left as an exercise to readers of the doc. Importantly, unlike some solutions already discussed in #945, nothing about this is application-specific. The example LazyGroup implementation does not encode any knowledge about the structure of the codebase in which it is used, which means that users can copy-paste the example and expect it to work (within reason). Because this also introduces the risk of reckless copy-paste by novice users, a warning is included in the doc that is meant to point at a certain level of application maturity which should be reached before this strategy can be safely applied.

authored by Stephen Rosen · committed by David Lord · parent 6ae9428 · 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.. click:example::249250 # 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.. click:example::296297 # 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.