Skip to content
Myr

remove mentions of deprecated base classes

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

authored by David Lord · committed by David Lord · parent 9e0d0b2 · Browse files · 10 files+194 added−217 removed
This commit

State

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

Diff stats

10 files+194 added−217 removed

  • tests:+2 added−2 removed
  • other:+192 added−215 removed

10 files+194 added−217 removed

modified:docs/advanced.rst+33 added-26 removed
5 unmodified lines
6In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.91011.. _aliases:1213Command Aliases14---------------1515Many tools support aliases for commands (see `Command alias example16<https://github.com/pallets/click/tree/main/examples/aliases>`_).17For instance, you can configure ``git`` to accept ``git ci`` as alias for18``git commit``. Other tools also support auto-discovery for aliases by19automatically shortening them.16Many tools support aliases for commands. For example, you can configure17``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also18support auto-discovery for aliases by automatically shortening them.1921Click does not support this out of the box, but it's very easy to customize22the :class:`Group` or any other :class:`MultiCommand` to provide this23functionality.20It's possible to customize :class:`Group` to provide this functionality. As21explained in :ref:`custom-groups`, a group provides two methods:22:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular23case, you only need to override the latter as you generally don't want to24enumerate the aliases on the help page in order to avoid confusion.2525As explained in :ref:`custom-multi-commands`, a multi command can provide26two methods: :meth:`~MultiCommand.list_commands` and27:meth:`~MultiCommand.get_command`. In this particular case, you only need28to override the latter as you generally don't want to enumerate the29aliases on the help page in order to avoid confusion.26The following example implements a subclass of :class:`Group` that accepts a27prefix for a command. If there was a command called ``push``, it would accept28``pus`` as an alias (so long as it was unique):2931This following example implements a subclass of :class:`Group` that32accepts a prefix for a command. If there were a command called ``push``,33it would accept ``pus`` as an alias (so long as it was unique):3430.. click:example::3132 class AliasedGroup(click.Group):33 def get_command(self, ctx, cmd_name):39 rv = click.Group.get_command(self, ctx, cmd_name)34 rv = super().get_command(ctx, cmd_name)3536 if rv is not None:37 return rv3839 matches = [42 matches = [x for x in self.list_commands(ctx)43 if x.startswith(cmd_name)]40 x for x in self.list_commands(ctx)41 if x.startswith(cmd_name)42 ]4344 if not matches:45 return None4646 elif len(matches) == 1:47 if len(matches) == 1:48 return click.Group.get_command(self, ctx, matches[0])4950 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")5152 def resolve_command(self, ctx, args):53 # always return the full command name54 _, cmd, args = super().resolve_command(ctx, args)55 return cmd.name, cmd, args5655And it can then be used like this:57It can be used like this:5859.. click:example::6059 @click.command(cls=AliasedGroup)61 @click.group(cls=AliasedGroup)62 def cli():63 pass6463 @cli.command()65 @cli.command66 def push():67 pass6867 @cli.command()69 @cli.command70 def pop():71 pass7273See the `alias example`_ in Click's repository for another example.7475.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases767778Parameter Modifications79-----------------------8081Parameters (options and arguments) are forwarded to the command callbacks
190 unmodified lines
272273This can generally be activated in two different ways:2742751. It can be enabled on custom :class:`Command` subclasses by changing269 the :attr:`~BaseCommand.ignore_unknown_options` attribute.276 the :attr:`~Command.ignore_unknown_options` attribute.2772. It can be enabled by changing the attribute of the same name on the278 context class (:attr:`Context.ignore_unknown_options`). This is best279 changed through the ``context_settings`` dictionary on the command.280
215 unmodified lines
modified:docs/commands.rst+126 added-157 removed
1 unmodified line
2===================34.. currentmodule:: click56The most important feature of Click is the concept of arbitrarily nesting7command line utilities. This is implemented through the :class:`Command`8and :class:`Group` (actually :class:`MultiCommand`).6The structure of a Click application is defined with :class:`Command`, which7defines an individual named command, and :class:`Group`, which defines a nested8collection of commands (or more groups) under a name.91011Callback Invocation12-------------------1314For a regular command, the callback is executed whenever the command runs.15If the script is the only command, it will always fire (unless a parameter16callback prevents it. This for instance happens if someone passes17``--help`` to the script).1818For groups and multi commands, the situation looks different. In this case,19the callback fires whenever a subcommand fires (unless this behavior is20changed). What this means in practice is that an outer command runs21when an inner command runs:19For groups, the situation looks different. In this case, the callback fires20whenever a subcommand fires. What this means in practice is that an outer21command runs when an inner command runs:2223.. click:example::2425 @click.group()
121 unmodified lines
147148Group Invocation Without Command149--------------------------------150151By default, a group or multi command is not invoked unless a subcommand is152passed. In fact, not providing a command automatically passes ``--help``153by default. This behavior can be changed by passing154``invoke_without_command=True`` to a group. In that case, the callback is155always invoked instead of showing the help page. The context object also156includes information about whether or not the invocation would go to a157subcommand.151By default, a group is not invoked unless a subcommand is passed. In fact, not152providing a command automatically passes ``--help`` by default. This behavior153can be changed by passing ``invoke_without_command=True`` to a group. In that154case, the callback is always invoked instead of showing the help page. The155context object also includes information about whether or not the invocation156would go to a subcommand.157159Example:160158.. click:example::159160 @click.group(invoke_without_command=True)161 @click.pass_context
6 unmodified lines
168 @cli.command()169 def sync():170 click.echo('The subcommand')171175And how it works in practice:176172.. click:run::173174 invoke(cli, prog_name='tool', args=[])175 invoke(cli, prog_name='tool', args=['sync'])176182.. _custom-multi-commands:177184Custom Multi Commands185---------------------178.. _custom-groups:179187In addition to using :func:`click.group`, you can also build your own188custom multi commands. This is useful when you want to support commands189being loaded lazily from plugins.180Custom Groups181-------------182191A custom multi command just needs to implement a list and load method:183You can customize the behavior of a group beyond the arguments it accepts by184subclassing :class:`click.Group`.185193.. click:example::186The most common methods to override are :meth:`~click.Group.get_command` and187:meth:`~click.Group.list_commands`.188195 import click196 import os189The following example implements a basic plugin system that loads commands from190Python files in a folder. The command is lazily loaded to avoid slow startup.191198 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')192.. code-block:: python193200 class MyCLI(click.MultiCommand):194 import importlib.util195 import os196 import click197198 class PluginGroup(click.Group):199 def __init__(self, name=None, plugin_folder="commands", **kwargs):200 super().__init__(name=name, **kwargs)201 self.plugin_folder = plugin_folder202203 def list_commands(self, ctx):204 rv = []205204 for filename in os.listdir(plugin_folder):205 if filename.endswith('.py') and filename != '__init__.py':206 for filename in os.listdir(self.plugin_folder):207 if filename.endswith(".py"):208 rv.append(filename[:-3])209210 rv.sort()211 return rv212213 def get_command(self, ctx, name):211 ns = {}212 fn = os.path.join(plugin_folder, name + '.py')213 with open(fn) as f:214 code = compile(f.read(), fn, 'exec')215 eval(code, ns, ns)216 return ns['cli']214 path = os.path.join(self.plugin_folder, f"{name}.py")215 spec = importlib.util.spec_from_file_location(name, path)216 module = importlib.util.module_from_spec(spec)217 spec.loader.exec_module(module)218 return module.cli219218 cli = MyCLI(help='This tool\'s subcommands are loaded from a '219 'plugin folder dynamically.')220 cli = PluginGroup(221 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")222 )223221 if __name__ == '__main__':224 if __name__ == "__main__":225 cli()226224These custom classes can also be used with decorators:227Custom classes can also be used with decorators:228226.. click:example::229.. code-block:: python230228 @click.command(cls=MyCLI)231 @click.group(232 cls=PluginGroup,233 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")234 )235 def cli():236 pass237232Merging Multi Commands233----------------------238235In addition to implementing custom multi commands, it can also be236interesting to merge multiple together into one script. While this is237generally not as recommended as it nests one below the other, the merging238approach can be useful in some circumstances for a nicer shell experience.239.. _command-chaining:240240The default implementation for such a merging system is the241:class:`CommandCollection` class. It accepts a list of other multi242commands and makes the commands available on the same level.241Command Chaining242----------------243244Example usage:244It is useful to invoke more than one subcommand in one call. For example,245``my-app validate build upload`` would invoke ``validate``, then ``build``, then246``upload``. To implement this, pass ``chain=True`` when creating a group.247248.. click:example::249248 import click249250 @click.group()251 def cli1():250 @click.group(chain=True)251 def cli():252 pass253254 @cli1.command()255 def cmd1():256 """Command on cli1"""254 @cli.command('validate')255 def validate():256 click.echo('validate')257258 @click.group()259 def cli2():260 pass258 @cli.command('build')259 def build():260 click.echo('build')261262 @cli2.command()263 def cmd2():264 """Command on cli2"""262You can invoke it like this:263266 cli = click.CommandCollection(sources=[cli1, cli2])267268 if __name__ == '__main__':269 cli()270271And what it looks like:272264.. click:run::265275 invoke(cli, prog_name='cli', args=['--help'])266 invoke(cli, prog_name='my-app', args=['validate', 'build'])267277In case a command exists in more than one source, the first source wins.268When using chaining, there are a few restrictions:269270- Only the last command may use ``nargs=-1`` on an argument, otherwise the271 parser will not be able to find further commands.272- It is not possible to nest groups below a chain group.273- On the command line, options must be specified before arguments for each274 command in the chain.275- The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the276 parser doesn't know the full list of commands that will run yet.277280.. _multi-command-chaining:278282Multi Command Chaining283----------------------279Command Pipelines280-----------------281285.. versionadded:: 3.0282When using chaining, a common pattern is to have each command process the283result of the previous command.284287Sometimes it is useful to be allowed to invoke more than one subcommand in288one go. For example, ``my-app validate build upload`` would invoke ``validate``,289then ``build``, then ``upload``. To implement this in Click, pass ``chain=True``290when creating a group.285A straightforward way to do this is to use :func:`make_pass_decorator` to pass286a context object to each command, and store and read the data on that object.287288.. click:example::289290 pass_ns = click.make_pass_decorator(dict, ensure=True)291292 @click.group(chain=True)295 def cli():296 pass293 @click.argument("name")294 @pass_ns295 def cli(ns, name):296 ns["name"] = name297298 @cli.command299 @pass_ns300 def lower(ns):301 ns["name"] = ns["name"].lower()302299 @cli.command('sdist')300 def sdist():301 click.echo('sdist called')303 @cli.command304 @pass_ns305 def show(ns):306 click.echo(ns["name"])307303304 @cli.command('bdist_wheel')305 def bdist_wheel():306 click.echo('bdist_wheel called')307308Now you can invoke it like this:309308.. click:run::309312 invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])310 invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])311314When using multi command chaining you can only have one command (the last)315use ``nargs=-1`` on an argument. It is also not possible to nest multi316commands below chained multicommands. Other than that there are no317restrictions on how they work. They can accept options and arguments as318normal. The order between options and arguments is limited for chained319commands. Currently only ``--options argument`` order is allowed.312Another way to do this is to collect data returned by each command, then process313it at the end of the chain. Use the group's :meth:`~Group.result_callback`314decorator to register a function that is called after the chain is finished. It315is passed the list of return values as well as any parameters registered on the316group.317321Another note: the :attr:`Context.invoked_subcommand` attribute is a bit322useless for multi commands as it will give ``'*'`` as value if more than323one command is invoked. This is necessary because the handling of324subcommands happens one after another so the exact subcommands that will325be handled are not yet available when the callback fires.318A command can return anything, including a function. Here's an example of that,319where each subcommand creates a function that processes the input, then the320result callback calls each function. The command takes a file, processes each321line, then outputs it. If no subcommands are given, it outputs the contents322of the file unchanged.323327.. note::324.. code-block:: python325329 It is currently not possible for chain commands to be nested. This330 will be fixed in future versions of Click.331332333Multi Command Pipelines334-----------------------335336.. versionadded:: 3.0337338A very common usecase of multi command chaining is to have one command339process the result of the previous command. There are various ways in340which this can be facilitated. The most obvious way is to store a value341on the context object and process it from function to function. This342works by decorating a function with :func:`pass_context` after which the343context object is provided and a subcommand can store its data there.344345Another way to accomplish this is to setup pipelines by returning346processing functions. Think of it like this: when a subcommand gets347invoked it processes all of its parameters and comes up with a plan of348how to do its processing. At that point it then returns a processing349function and returns.350351Where do the returned functions go? The chained multicommand can register352a callback with :meth:`MultiCommand.result_callback` that goes over all353these functions and then invoke them.354355To make this a bit more concrete consider this example:356357.. click:example::358326 @click.group(chain=True, invoke_without_command=True)360 @click.option('-i', '--input', type=click.File('r'))361 def cli(input):327 @click.argument("fin", type=click.File("r"))328 def cli(fin):329 pass330331 @cli.result_callback()365 def process_pipeline(processors, input):366 iterator = (x.rstrip('\r\n') for x in input)332 def process_pipeline(processors, fin):333 iterator = (x.rstrip("\r\n") for x in input)334335 for processor in processors:336 iterator = processor(iterator)337338 for item in iterator:339 click.echo(item)340372 @cli.command('uppercase')341 @cli.command("upper")342 def make_uppercase():343 def processor(iterator):344 for line in iterator:345 yield line.upper()346 return processor347379 @cli.command('lowercase')348 @cli.command("lower")349 def make_lowercase():350 def processor(iterator):351 for line in iterator:352 yield line.lower()353 return processor354386 @cli.command('strip')355 @cli.command("strip")356 def make_strip():357 def processor(iterator):358 for line in iterator:359 yield line.strip()
26 unmodified lines
386make resource handling much more complicated. For such it's recommended387to not use the file type and manually open the file through388:func:`open_file`.389421For a more complex example that also improves upon handling of the422pipelines have a look at the `imagepipe multi command chaining demo423<https://github.com/pallets/click/tree/main/examples/imagepipe>`__ in424the Click repository. It implements a pipeline based image editing tool425that has a nice internal structure for the pipelines.390For a more complex example that also improves upon handling of the pipelines,391see the `imagepipe example`_ in the Click repository. It implements a392pipeline based image editing tool that has a nice internal structure.393394.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe395396397Overriding Defaults398-------------------399400By default, the default value for a parameter is pulled from the
100 unmodified lines
501that were previously hard to implement.502503In essence any command callback can now return a value. This return value504is bubbled to certain receivers. One usecase for this has already been536show in the example of :ref:`multi-command-chaining` where it has been537demonstrated that chained multi commands can have callbacks that process505show in the example of :ref:`command-chaining` where it has been506demonstrated that chained groups can have callbacks that process507all return values.508509When working with command return values in Click, this is what you need to510know:511512- The return value of a command callback is generally returned from the544 :meth:`BaseCommand.invoke` method. The exception to this rule has to513 :meth:`Command.invoke` method. The exception to this rule has to514 do with :class:`Group`\s:515516 * In a group the return value is generally the return value of the517 subcommand invoked. The only exception to this rule is that the
1 unmodified line
519 invoked without arguments and `invoke_without_command` is enabled.520 * If a group is set up for chaining then the return value is a list521 of all subcommands' results.522 * Return values of groups can be processed through a554 :attr:`MultiCommand.result_callback`. This is invoked with the523 :attr:`Group.result_callback`. This is invoked with the524 list of all return values in chain mode, or the single return525 value in case of non chained commands.526527- The return value is bubbled through from the :meth:`Context.invoke`
1 unmodified line
529 where you internally want to call into another command.530531- Click does not have any hard requirements for the return values and532 does not use them itself. This allows return values to be used for564 custom decorators or workflows (like in the multi command chaining533 custom decorators or workflows (like in the command chaining534 example).535536- When a Click script is invoked as command line application (through568 :meth:`BaseCommand.main`) the return value is ignored unless the537 :meth:`Command.main`) the return value is ignored unless the538 `standalone_mode` is disabled in which case it's bubbled through.
modified:docs/complex.rst+15 added-9 removed
222 unmodified lines
223--------------------------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.227: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.233
44 unmodified lines
278 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):282 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 )
18 unmodified lines
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 LazyGroup323
4 unmodified lines
328 )329 def cli():330 pass331332.. code-block:: python333334 # in baz.py335 import click336337 @click.group(help="baz command for lazy example")
4 unmodified lines
342What triggers Lazy Loading?343```````````````````````````344345There are several events which may trigger lazy loading by running the340:meth:`MultiCommand.get_command` function.346: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``.
12 unmodified lines
363364It is possible to make the process even lazier, but it is generally more difficult the365more you want to defer work.366361For example, subcommands could be represented as a custom :class:`BaseCommand` subclass367For example, subcommands could be represented as a custom :class:`Command` subclass368which defers importing the command until it is invoked, but which provides363:meth:`BaseCommand.get_short_help_str` in order to support completions and helptext.369: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 importing
8 unmodified lines
382 from mylibrary import foo_concrete383384 foo_concrete(n, w)385380Because ``click`` builds helptext and usage info from options, arguments, and command386Because Click builds helptext and usage info from options, arguments, and command387attributes, it has no awareness that the underlying function is in any way handling a382deferred import. Therefore, all ``click``-provided utilities and functionality will work388deferred import. Therefore, all Click-provided utilities and functionality will work389as normal on such a command.
modified:docs/exceptions.rst+1 added-1 removed
8 unmodified lines
910Where are Errors Handled?11-------------------------1213Click's main error handling is happening in :meth:`BaseCommand.main`. In13Click's main error handling is happening in :meth:`Command.main`. In14there it handles all subclasses of :exc:`ClickException` as well as the15standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The16latter are internally translated into an :exc:`Abort`.17
56 unmodified lines
modified:docs/quickstart.rst+1 added-1 removed
91 unmodified lines
92* ``colors``: `Color support demo93 <https://github.com/pallets/click/tree/main/examples/colors>`_94* ``termui``: `Terminal UI functions demo95 <https://github.com/pallets/click/tree/main/examples/termui>`_96* ``imagepipe``: `Multi command chaining demo96* ``imagepipe``: `Command chaining demo97 <https://github.com/pallets/click/tree/main/examples/imagepipe>`_9899Basic Concepts - Creating a Command100-----------------------------------
176 unmodified lines
modified:docs/upgrading.rst+4 added-4 removed
40 unmodified lines
4142Upgrading to 3.243----------------4445Click 3.2 had to perform two changes to multi commands which were45Click 3.2 had to perform two changes to groups which were46triggered by a change between Click 2 and Click 3 that had bigger47consequences than anticipated.4849Context Invokes
21 unmodified lines
7172This also allowed us to fix the issue that defaults were not handled73properly by this function.7475Multicommand Chaining API76`````````````````````````75Command Chaining API76````````````````````7778Click 3 introduced multicommand chaining. This required a change in how78Click 3 introduced command chaining. This required a change in how79Click internally dispatches. Unfortunately this change was not correctly80implemented and it appeared that it was possible to provide an API that81can inform the super command about all the subcommands that will be82invoked.
49 unmodified lines
modified:examples/complex/complex/cli.py+1 added-1 removed
26 unmodified lines
27pass_environment = click.make_pass_decorator(Environment, ensure=True)28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))293031class ComplexCLI(click.MultiCommand):31class ComplexCLI(click.Group):32 def list_commands(self, ctx):33 rv = []34 for filename in os.listdir(cmd_folder):35 if filename.endswith(".py") and filename.startswith("cmd_"):
25 unmodified lines
modified:examples/imagepipe/README+1 added-1 removed
1$ imagepipe_23 imagepipe is an example application that implements some4 multi commands that chain image processing instructions4 commands that chain image processing instructions5 together.67 This requires pillow.8
5 unmodified lines
modified:src/click/core.py+10 added-15 removed
67 unmodified lines
68 base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False69) -> None:70 if not base_command.chain or not isinstance(cmd, Group):71 return7273 if register:73 hint = (74 "It is not possible to add multi commands as children to"75 " another multi command that is in chain mode."74 message = (75 f"It is not possible to add the group {cmd_name!r} to another"76 f" group {base_command.name!r} that is in chain mode."77 )78 else:78 hint = (79 "Found a multi command as subcommand to a multi command"80 " that is in chain mode. This is not supported."79 message = (80 f"Found the group {cmd_name!r} as subcommand to another group "81 f" {base_command.name!r} that is in chain mode. This is not supported."82 )82 raise RuntimeError(83 f"{hint}. Command {base_command.name!r} is set to chain and"84 f" {cmd_name!r} was added as a subcommand but it in itself is a"85 f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"86 f" within a chained {type(base_command).__name__} named"87 f" {base_command.name!r})."88 )8384 raise RuntimeError(message)858687def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:88 return list(zip(*repeat(iter(iterable), batch_size)))8990
1410 unmodified lines
1501 if self.chain:1502 for param in self.params:1503 if isinstance(param, Argument) and not param.required:1504 raise RuntimeError(1509 "Multi commands in chain mode cannot have"1510 " optional arguments."1505 "A group in chain mode cannot have optional arguments."1506 )15071508 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1509 info_dict = super().to_info_dict(ctx)
1481 unmodified lines
modified:tests/test_chain.py+2 added-2 removed
187 unmodified lines
188 assert not result.exception189 assert result.output.splitlines() == ["cli=", "a=", "b=", "c="]190191192def test_multicommand_arg_behavior(runner):192def test_group_arg_behavior(runner):193 with pytest.raises(RuntimeError):194195 @click.group(chain=True)196 @click.argument("forbidden", required=False)
21 unmodified lines
218 assert result.output.splitlines() == ["cli:foo", "a"]219220221@pytest.mark.xfail222def test_multicommand_chaining(runner):222def test_group_chaining(runner):223 @click.group(chain=True)224 def cli():225 debug()226
19 unmodified lines