Skip to content
Myr

💥 Make `typer-slim` a shallow wrapper around `typer`, always requiring `rich` and `shellingham` (#1522)

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

authored by Sofie Van Landeghem · committed by GitHub · parent d9b46c3 · Browse files · 21 files+129 added−144 removed
This commit

State

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

Trailers

  • Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
  • Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>

Diff stats

21 files+129 added−144 removed

  • other:+129 added−144 removed

21 files+129 added−144 removed

modified:.github/workflows/test-redistribute.yml-12 removed
modified:docs/tutorial/commands/help.md+4 added-5 removed
200 unmodified lines
201If there are multiple close matches, Typer will suggest them all. This feature uses Python's built-in `difflib.get_close_matches()` to find similar command names, making your CLI more user-friendly by helping users recover from typos.202203## Rich Markdown and Markup204205If you have **Rich** installed as described in [Printing and Colors](../printing.md){.internal-link target=_blank}, you can configure your app to enable markup text with the parameter `rich_markup_mode`.205Typer installs **Rich** to allow for more formatting in the docstrings and the `help` parameter for *CLI arguments* and *CLI options*. You will see more about it below. 👇206207Then you can use more formatting in the docstrings and the `help` parameter for *CLI arguments* and *CLI options*. You will see more about it below. 👇208207/// info208211By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed. In the latter case, you can set `rich_markup_mode` to `None` to disable rich text formatting.209You can disable rich text formatting by setting `rich_markup_mode` to `None` for your specific app.210Alternatively, you can disable it globally using an environmental variable `TYPER_USE_RICH` set to `False` or `0`.211212///213214### Rich Markup215217If you set `rich_markup_mode="rich"` when creating the `typer.Typer()` app, you will be able to use <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich Console Markup</a> in the docstring, and even in the help for the *CLI arguments* and options:216If you set `rich_markup_mode="rich"` when creating the `typer.Typer()` app (which is the default), you will be able to use <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich Console Markup</a> in the docstring, and even in the help for the *CLI arguments* and options:217218{* docs_src/commands/help/tutorial004_an_py39.py hl[5,11,15:17,22,25,28] *}219220With that, you can use <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich Console Markup</a> to format the text in the docstring for the command `create`, make the word "`create`" bold and green, and even use an <a href="https://rich.readthedocs.io/en/stable/markup.html#emoji" class="external-link" target="_blank">emoji</a>.
284 unmodified lines
modified:docs/tutorial/options/help.md+1 added-1 removed
52 unmodified lines
53## *CLI Options* help panels5455The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.5657If you have installed Rich as described in the docs for [Printing and Colors](../printing.md){.internal-link target=_blank}, you can set the `rich_help_panel` parameter to the name of the panel you want for each *CLI option*:57Using Rich, you can set the `rich_help_panel` parameter to the name of the panel you want for each *CLI option*:5859{* docs_src/options/help/tutorial002_an_py39.py hl[15,21] *}6061Now, when you check the `--help` option, you will see a default panel named "`Options`" for the *CLI options* that don't have a custom `rich_help_panel`.
104 unmodified lines
modified:docs/tutorial/exceptions.md+4 added-2 removed
12 unmodified lines
13This code is broken because you can't sum a string and a number (`name + 3`).1415## Exceptions with Rich1617If you have **Rich** installed (for example if you installed `"typer[all]"`), **Typer** will use it to automatically show you nicely printed errors.17**Typer** will automatically use Rich to automatically show you nicely printed errors.1819It will **omit** all the parts of the traceback (the chain of things that called your function) that come from the internal parts in Typer and Click.2021So, the error you see will be **much clearer** and simpler, to help you detect the problem in your code quickly:
24 unmodified lines
46</div>4748## Exceptions without Rich4950If you don't have Rich installed, Typer will still do some tricks to show you the information **as clearly as possible**:50You can disable Rich globally using the environmental variable `TYPER_USE_RICH`.5152In this case, Typer will still do some tricks to show you the information **as clearly as possible**:5354<div class="termy">5556```console57$ python main.py
218 unmodified lines
modified:docs/tutorial/install.md-10 removed
modified:docs/tutorial/options-autocompletion.md+1 added-1 removed
298 unmodified lines
299{* docs_src/options_autocompletion/tutorial008_an_py39.py hl[12,15:16] *}300301/// info302303If you can't install and use Rich, you can also use `print(lastname, file=sys.stderr)` or `typer.echo("some text", err=True)` instead.303If you have disabled Rich, you can also use `print(lastname, file=sys.stderr)` or `typer.echo("some text", err=True)` instead.304305///306307We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `list[str]`, here it's named `args`.
89 unmodified lines
modified:docs/tutorial/package.md-6 removed
610 unmodified lines
611You just have to pass it the module to import (`rick_portal_gun.main`) and it will detect the `typer.Typer` app automatically.612613By specifying the `--name` of the program it will be able to use it while generating the docs.614615/// tip616617If you installed `typer-slim` and don't have the `typer` command, you can use `python -m typer` instead.618619///620615### Publish a new version with the docs616617Now you can publish a new version with the updated docs.618
54 unmodified lines
modified:docs/tutorial/printing.md+1 added-1 removed
110 unmodified lines
111In general, **Typer** tends to be the entry point to your program, taking the first input from the user.112113**Rich** is useful for the parts that need to *display* information. Showing beautiful content on the screen.114115The best results for your command line application would be achieved combining both **Typer** and **Rich**.115The best results for your command line application are achieved combining both **Typer** and **Rich**.116117## "Standard Output" and "Standard Error"118119The way printing works underneath is that the **operating system** (Linux, Windows, macOS) treats what we print as if our CLI program was **writing text** to a "**virtual file**" called "**standard output**".
165 unmodified lines
modified:docs/tutorial/progressbar.md+1 added-1 removed
73 unmodified lines
74If you can use Rich, use the information above, the Rich docs, and skip the rest of this page. 😎7576///7778But if you can't use Rich, Typer (actually Click) comes with a simple utility to show progress bars.78But if you can't use Rich and have it disabled, Typer (actually Click) comes with a simple utility to show progress bars.7980/// info8182`typer.progressbar()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/8.1.x/utils/#showing-progress-bars" class="external-link" target="_blank">Click's docs</a>.
156 unmodified lines
modified:docs/tutorial/prompt.md+1 added-1 removed
73 unmodified lines
74</div>7576## Prompt with Rich7778If you installed Rich as described in [Printing and Colors](printing.md){.internal-link target=_blank}, you can use Rich to prompt the user for input:78You can use Rich to prompt the user for input:7980{* docs_src/prompt/tutorial004_py39.py hl[2,9] *}8182And when you run it, it will look like:
12 unmodified lines
modified:docs/tutorial/typer-command.md+2 added-8 removed
16 unmodified lines
17```1819...it includes the `typer` command.2021If you don't want to have the `typer` command, you can install instead:21If you don't want to use the `typer` command, you can call the Typer library as a module with:2223```bash24pip install typer-slim25```2627You can still use it by calling the Typer library as a module with:2829```bash24python -m typer25```2627## Install completion
226 unmodified lines
254</div>255256/// tip257264If you installed only `typer-slim` and you don't have the `typer` command, you can still generate docs with:258If you don't want to use the `typer` command, you can still generate docs with:259260```console261$ python -m typer some_script.py utils docs262```
111 unmodified lines
modified:docs/features.md+1 added-8 removed
52 unmodified lines
53/// note | * Auto completion5455Auto completion works when you create a package (installable with `pip`). Or when using the `typer` command.5657**Typer** uses `shellingham` to auto-detect the current shell when installing completion. If you don't want to include `shellingham`, install `typer-slim`.57**Typer** uses `shellingham` to auto-detect the current shell when installing completion.5859**Typer** will automatically create 2 *CLI options*:6061* `--install-completion`: Install completion for the current shell.62* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.6364If you didn't add `shellingham` (if you installed `pip install typer-slim`) those *CLI options* take a value with the name of the shell to install completion for, e.g.:6566* `--install-completion bash`.67* `--show-completion powershell`.6869Then you can tell the user to install completion after installing your CLI program and the rest will just work.7064///6566/// tip67
19 unmodified lines
modified:docs/index.md+5 added-20 removed
360 unmodified lines
361For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.362363## Dependencies364365**Typer** stands on the shoulders of a giant. Its only internal required dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.365**Typer** stands on the shoulders of giants. It has three required dependencies:366367By default it also comes with extra standard dependencies:368367* <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>: a popular tool for building CLIs in Python. Typer is based on it.368* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.369* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: to automatically detect the current shell when installing completion.371 * With `shellingham` you can just use `--install-completion`.372 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.370371### `typer-slim`372376If you don't want the extra standard optional dependencies, install `typer-slim` instead.373There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.374378When you install with:375However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.376380```bash381pip install typer382```377If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.378384...it includes the same code and dependencies as:385386```bash387pip install "typer-slim[standard]"388```389390The `standard` extra dependencies are `rich` and `shellingham`.391392**Note**: The `typer` command is only included in the `typer` package.393379## License380381This project is licensed under the terms of the MIT license.
modified:typer/_completion_shared.py+7 added-13 removed
4 unmodified lines
5from pathlib import Path6from typing import Optional, Union78import click9from typer.core import HAS_SHELLINGHAM9import shellingham1011if HAS_SHELLINGHAM:12 import shellingham111412class Shells(str, Enum):13 bash = "bash"14 zsh = "zsh"15 fish = "fish"
226 unmodified lines
242 The name will always be lowercase. If the shell cannot be detected, None is243 returned.244 """245 name: Union[str, None] # N.B. shellingham is untyped249 if HAS_SHELLINGHAM:250 try:251 # N.B. detect_shell returns a tuple of (shell name, shell command).252 # We only need the name.253 name, _cmd = shellingham.detect_shell() # noqa: TID251254 except shellingham.ShellDetectionFailure: # pragma: no cover255 name = None246 try:247 # N.B. detect_shell returns a tuple of (shell name, shell command).248 # We only need the name.249 name, _cmd = shellingham.detect_shell() # noqa: TID251250 except shellingham.ShellDetectionFailure: # pragma: no cover251 name = None256 else:257 name = None # pragma: no cover252253 return name
modified:typer/completion.py+1 added-2 removed
5 unmodified lines
6import click78from ._completion_classes import completion_init9from ._completion_shared import Shells, _get_shell_name, get_completion_script, install10from .core import HAS_SHELLINGHAM10from .models import ParamMeta11from .params import Option12from .utils import get_params_from_function13
2 unmodified lines
1617def get_completion_inspect_parameters() -> tuple[ParamMeta, ParamMeta]:18 completion_init()19 test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")21 if HAS_SHELLINGHAM and not test_disable_detection:20 if not test_disable_detection:21 parameters = get_params_from_function(_install_completion_placeholder_function)22 else:23 parameters = get_params_from_function(24 _install_completion_no_auto_placeholder_function
122 unmodified lines
modified:typer/core.py+1 added-3 removed
1import errno2import importlib.util2import inspect3import os4import sys5from collections.abc import MutableMapping, Sequence
20 unmodified lines
2627MarkupMode = Literal["markdown", "rich", None]28MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"2931HAS_RICH = importlib.util.find_spec("rich") is not None32HAS_SHELLINGHAM = importlib.util.find_spec("shellingham") is not None30HAS_RICH = os.getenv("TYPER_USE_RICH", True)3132if HAS_RICH:33 DEFAULT_MARKUP_MODE: MarkupMode = "rich"34else: # pragma: no cover
804 unmodified lines
modified:typer-cli/README.md+2 added
26 unmodified lines
27---2829Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.3031It's also a command line tool to run scripts, automatically converting them to CLI applications.3233## Typer CLI3435⚠️ Do not install this package. ⚠️36
19 unmodified lines
added:typer-slim/README.md+57 added
1<p align="center">2 <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" alt="Typer"></a>3</p>4<p align="center">5 <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>6</p>7<p align="center">8<a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank">9 <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">10</a>11<a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish" target="_blank">12 <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish">13</a>14<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer" target="_blank">15 <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage">16<a href="https://pypi.org/project/typer" target="_blank">17 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">18</a>19</p>2021---2223**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com/tutorial/typer-command/</a>2425**Source Code**: <a href="https://github.com/fastapi/typer" target="_blank">https://github.com/fastapi/typer</a>2627---2829Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.3031It's also a command line tool to run scripts, automatically converting them to CLI applications.3233## `typer-slim`3435⚠️ Do not install this package. ⚠️3637This package, `typer-slim`, does nothing other than depend on `typer`.3839There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.4041However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.4243If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.4445The only reason this package exists is as a migration path for old projects that used to depend on `typer-slim`, so that they can get the latest version of `typer`.4647You probably **should not** install this package.4849Install instead:5051```bash52pip install typer53```5455## License5657This project is licensed under the terms of the MIT license.
modified:pdm_build.py+9 added-16 removed
4 unmodified lines
56TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "typer")789def pdm_build_initialize(context: Context):9def pdm_build_initialize(context: Context) -> None:10 metadata = context.config.metadata11 # Get main version12 version = metadata["version"]13 # Get package names to keep in sync with the same main version14 sync_dependencies: list[str] = context.config.data["tool"]["tiangolo"][15 "_internal-slim-build"16 ]["sync-dependencies"]17 # Get custom config for the current package, from the env var18 config: dict[str, Any] = context.config.data["tool"]["tiangolo"][18 all_configs_config: dict[str, Any] = context.config.data["tool"]["tiangolo"][19 "_internal-slim-build"20 ]["packages"][TIANGOLO_BUILD_PACKAGE]20 ]["packages"]2122 if TIANGOLO_BUILD_PACKAGE not in all_configs_config:23 return2425 config = all_configs_config[TIANGOLO_BUILD_PACKAGE]26 project_config: dict[str, Any] = config["project"]22 # Get main optional dependencies, extras23 optional_dependencies: dict[str, list[str]] = metadata.get(24 "optional-dependencies", {}25 )26 # Get custom optional dependencies name to always include in this (non-slim) package27 include_optional_dependencies: list[str] = config.get(28 "include-optional-dependencies", []29 )27 # Override main [project] configs with custom configs for this package28 for key, value in project_config.items():29 metadata[key] = value30 # Get custom build config for the current package
4 unmodified lines
35 for key, value in build_config.items():36 context.config.build_config[key] = value37 # Get main dependencies38 dependencies: list[str] = metadata.get("dependencies", [])42 # Add optional dependencies to the default dependencies for this (non-slim) package43 for include_optional in include_optional_dependencies:44 optional_dependencies_group = optional_dependencies.get(include_optional, [])45 dependencies.extend(optional_dependencies_group)39 # Sync versions in dependencies40 new_dependencies = []41 for dep in dependencies:42 if dep in sync_dependencies:50 new_dep = f"{dep}=={version}"43 new_dep = f"{dep}>={version}"44 new_dependencies.append(new_dep)45 else:46 new_dependencies.append(dep)47 if new_dependencies != dependencies:
1 unmodified line
modified:pyproject.toml+26 added-14 removed
33 unmodified lines
34 "Programming Language :: Python :: 3.14",35]36dependencies = [37 "click >= 8.0.0",38 "shellingham >=1.3.0",39 "rich >=10.11.0",40 "annotated-doc >=0.0.2",41]42readme = "README.md"43
3 unmodified lines
47Repository = "https://github.com/fastapi/typer"48Issues = "https://github.com/fastapi/typer/issues"49Changelog = "https://typer.tiangolo.com/release-notes/"5049[project.optional-dependencies]50standard = [51 "shellingham >=1.3.0",52 "rich >=10.11.0",53]51[project.scripts]52typer = "typer.cli:main"5354[dependency-groups]55dev = [56 { include-group = "tests" },
45 unmodified lines
102]103104[tool.tiangolo._internal-slim-build]105sync-dependencies = [107 "typer-slim[standard]",108 "typer-cli",106 "typer"107]108109[tool.tiangolo._internal-slim-build.packages.typer-slim.project]110name = "typer-slim"114115[tool.tiangolo._internal-slim-build.packages.typer]116include-optional-dependencies = ["standard"]117118[tool.tiangolo._internal-slim-build.packages.typer.project]111readme = "typer-slim/README.md"112dependencies = [113 "typer",114]115optional-dependencies = {}116scripts = {}117121[tool.tiangolo._internal-slim-build.packages.typer.project.scripts]122typer = "typer.cli:main"118[tool.tiangolo._internal-slim-build.packages.typer-slim.tool.pdm.build]119# excludes needs to explicitly exclude the top level python packages,120# otherwise PDM includes them by default121# A "*" glob pattern can't be used here because in PDM internals, the patterns are put122# in a set (unordered, order varies) and each excluded file is assigned one of the123# glob patterns that matches, as the set is unordered, the matched pattern could be "*"124# independent of the order here. And then the internal code would give it a lower score125# than the one for a default included file.126# By not using "*" and explicitly excluding the top level packages, they get a higher127# score than the default inclusion128excludes = ["typer", "tests", "pdm_build.py"]129# source-includes needs to explicitly define some value because PDM will check the130# truthy value of the list, and if empty, will include some defaults, including "tests",131# an empty string doesn't match anything, but makes the list truthy, so that PDM132# doesn't override it during the build.133source-includes = [""]134135[tool.tiangolo._internal-slim-build.packages.typer-cli.project]136name = "typer-cli"137readme = "typer-cli/README.md"138dependencies = [139 "typer",140]141optional-dependencies = {}142scripts = {}143144[tool.tiangolo._internal-slim-build.packages.typer-cli.tool.pdm.build]145# excludes needs to explicitly exclude the top level python packages,146# otherwise PDM includes them by default
125 unmodified lines
modified:README.md+5 added-20 removed
354 unmodified lines
355For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.356357## Dependencies358359**Typer** stands on the shoulders of a giant. Its only internal required dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.359**Typer** stands on the shoulders of giants. It has three required dependencies:360361By default it also comes with extra standard dependencies:362361* <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>: a popular tool for building CLIs in Python. Typer is based on it.362* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.363* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: to automatically detect the current shell when installing completion.365 * With `shellingham` you can just use `--install-completion`.366 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.364365### `typer-slim`366370If you don't want the extra standard optional dependencies, install `typer-slim` instead.367There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.368372When you install with:369However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.370374```bash375pip install typer376```371If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.372378...it includes the same code and dependencies as:379380```bash381pip install "typer-slim[standard]"382```383384The `standard` extra dependencies are `rich` and `shellingham`.385386**Note**: The `typer` command is only included in the `typer` package.387373## License374375This project is licensed under the terms of the MIT license.