Stable (#3159)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents f67abc6, f4a1bd4 · Browse files · 11 files·+317 added−219 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+317 added−219 removed
- tests:+44 added−0 removed
- other:+273 added−219 removed
Provenance
- Commit
6c894eb- Tree
1e24e4f- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
f67abc6- Parent 2
f4a1bd4
11 files changed+317 added−219 removed
added:docs/entry-points.md+88 added
1+# Packaging Entry Points2+3+```{eval-rst}4+.. currentmodule:: click5+```6+7+It's recommended to write command line utilities as installable packages with8+entry points instead of telling users to run ``python hello.py``.9+10+A distribution package is a ``.whl`` file you install with pip or another Python11+installer. You use a ``pyproject.toml`` file to describe the project and how it12+is built into a package. You might upload this package to PyPI, or distribute it13+to your users in another way.14+15+Python installers create executable scripts that will run a specified Python16+function. These are known as "entry points". The installer knows how to create17+an executable regardless of the operating system, so it will work on Linux,18+Windows, MacOS, etc.19+20+## Project Files21+22+To install your app with an entry point, all you need is the script and a23+``pyproject.toml`` file. Here's an example project directory:24+25+```text26+hello-project/27+ src/28+ hello/29+ __init__.py30+ hello.py31+ pyproject.toml32+```33+34+Contents of ``hello.py``:35+36+```{eval-rst}37+.. click:example::38+ import click39+40+ @click.command()41+ def cli():42+ """Prints a greeting."""43+ click.echo("Hello, World!")44+```45+46+Contents of ``pyproject.toml``:47+48+```toml49+[project]50+name = "hello"51+version = "1.0.0"52+description = "Hello CLI"53+requires-python = ">=3.11"54+dependencies = [55+ "click>=8.1",56+]57+58+[project.scripts]59+hello = "hello.hello:cli"60+61+[build-system]62+requires = ["flit_core<4"]63+build-backend = "flit_core.buildapi"64+```65+66+The magic is in the ``project.scripts`` section. Each line identifies one executable67+script. The first part before the equals sign (``=``) is the name of the script that68+should be generated, the second part is the import path followed by a colon69+(``:``) with the function to call (the Click command).70+71+## Installation72+73+When your package is installed, the installer will create an executable script74+based on the configuration. During development, you can install in editable75+mode using the ``-e`` option. Remember to use a virtual environment!76+77+```console78+$ python -m venv .venv79+$ . .venv/bin/activate80+$ pip install -e .81+```82+83+Afterwards, your command should be available:84+85+```console86+$ hello87+Hello, World!88+```deleted:docs/entry-points.rst-87 removed
1-Packaging Entry Points2-======================3-4-It's recommended to write command line utilities as installable packages with5-entry points instead of telling users to run ``python hello.py``.6-7-A distribution package is a ``.whl`` file you install with pip or another Python8-installer. You use a ``pyproject.toml`` file to describe the project and how it9-is built into a package. You might upload this package to PyPI, or distribute it10-to your users in another way.11-12-Python installers create executable scripts that will run a specified Python13-function. These are known as "entry points". The installer knows how to create14-an executable regardless of the operating system, so it will work on Linux,15-Windows, MacOS, etc.16-17-18-Project Files19--------------20-21-To install your app with an entry point, all you need is the script and a22-``pyproject.toml`` file. Here's an example project directory:23-24-.. code-block:: text25-26- hello-project/27- src/28- hello/29- __init__.py30- hello.py31- pyproject.toml32-33-Contents of ``hello.py``:34-35-.. click:example::36-37- import click38-39- @click.command()40- def cli():41- """Prints a greeting."""42- click.echo("Hello, World!")43-44-Contents of ``pyproject.toml``:45-46-.. code-block:: toml47-48- [project]49- name = "hello"50- version = "1.0.0"51- description = "Hello CLI"52- requires-python = ">=3.11"53- dependencies = [54- "click>=8.1",55- ]56-57- [project.scripts]58- hello = "hello.hello:cli"59-60- [build-system]61- requires = ["flit_core<4"]62- build-backend = "flit_core.buildapi"63-64-The magic is in the ``project.scripts`` section. Each line identifies one executable65-script. The first part before the equals sign (``=``) is the name of the script that66-should be generated, the second part is the import path followed by a colon67-(``:``) with the function to call (the Click command).68-69-70-Installation71-------------72-73-When your package is installed, the installer will create an executable script74-based on the configuration. During development, you can install in editable75-mode using the ``-e`` option. Remember to use a virtual environment!76-77-.. code-block:: console78-79- $ python -m venv .venv80- $ . .venv/bin/activate81- $ pip install -e .82-83-Afterwards, your command should be available:84-85-.. click:run::86-87- invoke(cli, prog_name="hello")added:docs/exceptions.md+136 added
1+(exception-handling-exit-codes)=2+3+# Exception Handling and Exit Codes4+5+```{eval-rst}6+.. currentmodule:: click7+```8+9+Click internally uses exceptions to signal various error conditions that10+the user of the application might have caused. Primarily this is things11+like incorrect usage.12+13+```{contents}14+:depth: 115+:local:16+```17+18+## Where are Errors Handled?19+20+Click's main error handling is happening in {meth}`Command.main`. In21+there it handles all subclasses of {exc}`ClickException` as well as the22+standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions. The23+latter are internally translated into an {exc}`Abort`.24+25+The logic applied is the following:26+27+1. If an {exc}`EOFError` or {exc}`KeyboardInterrupt` happens, reraise it28+ as {exc}`Abort`.29+2. If a {exc}`ClickException` is raised, invoke the30+ {meth}`ClickException.show` method on it to display it and then exit31+ the program with {attr}`ClickException.exit_code`.32+3. If an {exc}`Abort` exception is raised print the string ``Aborted!``33+ to standard error and exit the program with exit code ``1``.34+4. If it goes through well, exit the program with exit code ``0``.35+36+## What if I Don't Want That?37+38+Generally you always have the option to invoke the {meth}`Command.invoke`39+method yourself. For instance if you have a {class}`Command` you can40+invoke it manually like this:41+42+```python43+ctx = command.make_context("command-name", ["args", "go", "here"])44+with ctx:45+ result = command.invoke(ctx)46+```47+48+In this case exceptions will not be handled at all and bubbled up as you49+would expect.50+51+Starting with Click 3.0 you can also use the {meth}`Command.main` method52+but disable the standalone mode which will do two things: disable53+exception handling and disable the implicit {func}`sys.exit` at the end.54+55+So you can do something like this:56+57+```python58+command.main(59+ ["command-name", "args", "go", "here"],60+ standalone_mode=False,61+)62+```63+64+## Which Exceptions Exist?65+66+Click has two exception bases: {exc}`ClickException` which is raised for67+all exceptions that Click wants to signal to the user and {exc}`Abort`68+which is used to instruct Click to abort the execution.69+70+A {exc}`ClickException` has a {meth}`ClickException.show` method which71+can render an error message to stderr or the given file object. If you72+want to use the exception yourself for doing something check the API docs73+about what else they provide.74+75+The following common subclasses exist:76+77+- {exc}`UsageError` to inform the user that something went wrong.78+- {exc}`BadParameter` to inform the user that something went wrong with79+ a specific parameter. These are often handled internally in Click and80+ augmented with extra information if possible. For instance if those81+ are raised from a callback Click will automatically augment it with82+ the parameter name if possible.83+- {exc}`FileError` this is an error that is raised by the84+ {class}`FileType` if Click encounters issues opening the file.85+86+(help-page-exit-codes)=87+88+## Help Pages and Exit Codes89+90+Triggering the a help page intentionally (by passing in ``--help``)91+returns exit code 0. If a help page is displayed due to incorrect user92+input, the program returns exit code 2. See {ref}`exit-codes` for more93+general information.94+95+For clarity, here is an example.96+97+```{eval-rst}98+.. click:example::99+100+ @click.group('printer_group')101+ def printer_group():102+ pass103+104+ @printer_group.command('printer')105+ @click.option('--this')106+ def printer(this):107+ if this:108+ click.echo(this)109+110+.. click:run::111+ invoke(printer_group, args=['--help'])112+113+The above invocation returns exit code 0.114+115+.. click:run::116+ invoke(printer_group, args=[])117+```118+119+The above invocation returns exit code 2 since the user invoked the command incorrectly. However, since this is such a common error when first using a command, Click invokes the help page for the user. To see that `printer-group` is an invalid invocation, turn `no_args_is_help` off.120+121+```{eval-rst}122+.. click:example::123+124+ @click.group('printer_group', no_args_is_help=False)125+ def printer_group():126+ pass127+128+ @printer_group.command('printer')129+ @click.option('--this')130+ def printer(this):131+ if this:132+ click.echo(this)133+134+.. click:run::135+ invoke(printer_group, args=[])136+```deleted:docs/exceptions.rst-126 removed
1-.. _exception-handling-exit-codes:2-3-Exception Handling and Exit Codes4-==================================5-6-.. currentmodule:: click7-8-Click internally uses exceptions to signal various error conditions that9-the user of the application might have caused. Primarily this is things10-like incorrect usage.11-12-.. contents::13- :depth: 114- :local:15-16-Where are Errors Handled?17--------------------------18-19-Click's main error handling is happening in :meth:`Command.main`. In20-there it handles all subclasses of :exc:`ClickException` as well as the21-standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The22-latter are internally translated into an :exc:`Abort`.23-24-The logic applied is the following:25-26-1. If an :exc:`EOFError` or :exc:`KeyboardInterrupt` happens, reraise it27- as :exc:`Abort`.28-2. If a :exc:`ClickException` is raised, invoke the29- :meth:`ClickException.show` method on it to display it and then exit30- the program with :attr:`ClickException.exit_code`.31-3. If an :exc:`Abort` exception is raised print the string ``Aborted!``32- to standard error and exit the program with exit code ``1``.33-4. If it goes through well, exit the program with exit code ``0``.34-35-What if I don't want that?36---------------------------37-38-Generally you always have the option to invoke the :meth:`invoke` method39-yourself. For instance if you have a :class:`Command` you can invoke it40-manually like this::41-42- ctx = command.make_context('command-name', ['args', 'go', 'here'])43- with ctx:44- result = command.invoke(ctx)45-46-In this case exceptions will not be handled at all and bubbled up as you47-would expect.48-49-Starting with Click 3.0 you can also use the :meth:`Command.main` method50-but disable the standalone mode which will do two things: disable51-exception handling and disable the implicit :meth:`sys.exit` at the end.52-53-So you can do something like this::54-55- command.main(['command-name', 'args', 'go', 'here'],56- standalone_mode=False)57-58-Which Exceptions Exist?59------------------------60-61-Click has two exception bases: :exc:`ClickException` which is raised for62-all exceptions that Click wants to signal to the user and :exc:`Abort`63-which is used to instruct Click to abort the execution.64-65-A :exc:`ClickException` has a :meth:`~ClickException.show` method which66-can render an error message to stderr or the given file object. If you67-want to use the exception yourself for doing something check the API docs68-about what else they provide.69-70-The following common subclasses exist:71-72-* :exc:`UsageError` to inform the user that something went wrong.73-* :exc:`BadParameter` to inform the user that something went wrong with74- a specific parameter. These are often handled internally in Click and75- augmented with extra information if possible. For instance if those76- are raised from a callback Click will automatically augment it with77- the parameter name if possible.78-* :exc:`FileError` this is an error that is raised by the79- :exc:`FileType` if Click encounters issues opening the file.80-81-82-.. _help-page-exit-codes:83-84-Help Pages and Exit Codes85---------------------------86-87-Triggering the a help page intentionally (by passing in ``--help``) returns exit code 0. If a help page is displayed due to incorrect user input, the program returns exit code 2. See :ref:`exit-codes` for more general information.88-89-For clarity, here is an example.90-91-.. click:example::92-93- @click.group('printer_group')94- def printer_group():95- pass96-97- @printer_group.command('printer')98- @click.option('--this')99- def printer(this):100- if this:101- click.echo(this)102-103-.. click:run::104- invoke(printer_group, args=['--help'])105-106-The above invocation returns exit code 0.107-108-.. click:run::109- invoke(printer_group, args=[])110-111-The above invocation returns exit code 2 since the user invoked the command incorrectly. However, since this is such a common error when first using a command, Click invokes the help page for the user. To see that `printer-group` is an invalid invocation, turn `no_args_is_help` off.112-113-.. click:example::114-115- @click.group('printer_group', no_args_is_help=False)116- def printer_group():117- pass118-119- @printer_group.command('printer')120- @click.option('--this')121- def printer(this):122- if this:123- click.echo(this)124-125-.. click:run::126- invoke(printer_group, args=[])modified:docs/index.rst+2 added-1 removed
77 unmodified lines78 :maxdepth: 179 80 entry-points81 setuptools82+ upgrade-guides83 support-multiple-versions84 85 Conceptual Guides86 -------------------41 unmodified lines128 129 About Project130 ===============131 131-* This documentation is structured according to `Diataxis <https://diataxis.fr/>`_132+* This documentation is structured according to `Diataxis <https://diataxis.fr/>`_ and written with `MyST <https://myst-parser.readthedocs.io/en/latest/>`_133 134 * `Version Policy <https://palletsprojects.com/versions>`_135 136 * `Contributing <https://palletsprojects.com/contributing/>`_9 unmodified linesadded:docs/upgrade-guides.md+34 added
12345678910111213141516171819202122232425262728293031323334# Upgrade Guides
```{contents}:depth: 1:local: true```
## Upgrading 8.3.X to 9.0**This is under active construction and will not be finalized until 9.0.0 is released.**
This guide assumes the user is on version 8.3.X.
### Deprecations
For each deprecation, provide a brief explanation, and direct users to new function / class if available.- TBD
### Removals with prior deprecation
For each removal, provide a brief explanation, and direct users to new function / class if available. If possible, deprecate and remove in 10.0.0, rather than removing outright.- TBD
### Removals with no prior deprecation
The changes were not able to be deprecated prior to removal. Explain clearly why then were not able to be deprecated first.- TBD
### Changes
- TBD
### Fixes
- TBDmodified:src/click/core.py+6 added-3 removed
2775 unmodified lines2776 is_flag = False2777 # Implicitly a flag because secondary options names were given.2778 elif self.secondary_opts:2779 is_flag = True2780- # The option is explicitly not a flag. But we do not know yet if it needs a2781- # value or not. So we look at the default value to determine it.2780+2781+ # The option is explicitly not a flag, but to determine whether or not it needs2782+ # value, we need to check if `flag_value` or `default` was set. Either one is2783+ # sufficient.2784+ # Ref: https://github.com/pallets/click/issues/30842785 elif is_flag is False and not self._flag_needs_value:2783- self._flag_needs_value = self.default is UNSET2786+ self._flag_needs_value = flag_value is not UNSET or self.default is UNSET2787 2788 if is_flag:2789 # Set missing default for flags if not explicitly required or prompted.2790 if self.default is UNSET and not self.required and not self.prompt:628 unmodified linesmodified:tests/test_options.py+44 added
13 unmodified lines14 import click15 from click import Option16 from click import UNPROCESSED17 from click._utils import UNSET18+from click.testing import CliRunner19 20 21 def test_prefixes(runner):22 @click.command()2252 unmodified lines2275 2276 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2277 assert result.stdout == "frozenset()"2278 assert result.exit_code == 02279+2280+2281+@pytest.mark.parametrize(2282+ ("flag_type", "args", "expect_output"),2283+ [2284+ (str, [], "Default\n"),2285+ (str, ["--theflag"], "FlagValue\n"),2286+ (str, ["--theflag", "value"], "value\n"),2287+ (int, [], "0\n"),2288+ (int, ["--theflag"], "1\n"),2289+ (int, ["--theflag", "2"], "2\n"),2290+ ],2291+)2292+def test_flag_value_on_option_with_zero_or_one_args(flag_type, args, expect_output):2293+ """An option with flag_value and is_flag=False can be2294+ omitted or used with 0 or 1 args.2295+2296+ Regression test for https://github.com/pallets/click/issues/30842297+ """2298+ if flag_type is str:2299+ flagopt = click.option(2300+ "--theflag",2301+ type=str,2302+ is_flag=False,2303+ flag_value="FlagValue",2304+ default="Default",2305+ )2306+ elif flag_type is int:2307+ flagopt = click.option(2308+ "--theflag", type=int, is_flag=False, flag_value=1, default=02309+ )2310+ else:2311+ raise NotImplementedError(flag_type)2312+2313+ @click.command()2314+ @flagopt2315+ def cmd(theflag):2316+ click.echo(theflag)2317+2318+ runner = CliRunner()2319+ result = runner.invoke(cmd, args)2320+ assert result.exit_code == 02321+ assert result.output == expect_outputmodified:CHANGES.rst+5 added
1 .. currentmodule:: click2 3+Unreleased4+5+- Fix handling of ``flag_value`` when ``is_flag=False`` to allow such options to be6+ used without an explicit value. :issue:`3084`7+8 Version 8.3.19 --------------10 11 Released 2025-11-151304 unmodified linesmodified:pyproject.toml+1 added-1 removed
1 [project]2 name = "click"3-version = "8.3.1"3+version = "8.3.dev"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = "BSD-3-Clause"7 license-files = ["LICENSE.txt"]200 unmodified linesmodified:uv.lock+1 added-1 removed
165 unmodified lines166 ]167 168 [[package]]169 name = "click"170-version = "8.3.1"170+version = "8.3.dev0"171 source = { editable = "." }172 dependencies = [173 { name = "colorama", marker = "sys_platform == 'win32'" },174 ]1206 unmodified lines