How To¶
The examples below all reference this example Typer application:
1import typer
2import typing as t
3try:
4 from enum import StrEnum
5except ImportError:
6 from enum import Enum
7 class StrEnum(str, Enum):
8 pass
9from typing_extensions import Annotated
10
11app = typer.Typer(add_completion=False)
12
13class Kind(StrEnum):
14
15 ONE = "one"
16 TWO = "two"
17
18
19@app.callback()
20def callback(
21 arg: Annotated[Kind, typer.Argument(help="An argument.")],
22 flag: Annotated[bool, typer.Option(help="Flagged.")] = False,
23 switch: Annotated[
24 bool,
25 typer.Option("--switch", "-s", help="Switch.")
26 ] = False
27):
28 """This is the callback function."""
29 pass
30
31
32@app.command()
33def foo(
34 name: Annotated[
35 str,
36 typer.Option(..., help="The name of the item to foo.")
37 ]
38):
39 """This is the foo command."""
40 pass
41
42
43@app.command()
44def bar(
45 names: Annotated[
46 t.List[str],
47 typer.Option(..., help="The names of the items to bar.")
48 ],
49):
50 """This is the bar command."""
51 pass
52
53
54if __name__ == "__main__":
55 app()
Build to Multiple Formats¶
Sphinx caches directive output and reuses the results when building the documentation
to different formats (e.g. html, pdf or text). This causes problems with the way the typer directive
dynamically determines which render target to use based on the active builder. This can mean that if
you run sphinx-build for html and
latexpdf at the same time the pdf may not render all
typer helps as expected. To work around this you can do one of four things
Run sphinx-build for each format separately.
Use the
onlydirective in combination withtyper:preferredto specify builder specific content.Use the
--fresh-envoption to force sphinx to rebuild the directive output for each builder.Add the following code to your conf.py to remove the doctree between builders:
def setup(app): import shutil from pathlib import Path if Path(app.doctreedir).exists(): shutil.rmtree(app.doctreedir)
Change the Width¶
The typer:width parameter defines the console character length rich
uses when it generates the console output. If your image is too wide, you can reduce the width by
setting the typer:width parameter to a smaller value. For example, for
sphinx-rtd-theme theme a width parameter of 65 works well:
.. typer:: examples.example:app
:width: 65
.. typer:: examples.example:app
:width: 100
Render Subcommand Structure¶
Add the typer:show-nested and typer:make-sections options to the typer
directive. This will render all subcommands as sections.
.. typer:: examples.example:app
:width: 65
:show-nested:
:make-sections:
example¶
foo¶
bar¶
Tip
See Cross-Referencing Commands for information on how to cross reference sections.
Render a Single Subcommand¶
Subcommands can be rendered individually:
.. typer:: examples.example:app:bar
:width: 65
:show-nested:
:make-sections:
example bar¶
Render as HTML¶
By default for html builders, svg output is generated. HTML output is also supported, but requires
rendering the html output into an iframe to isolate the generated css. The iframe heights can be
given directly using the typer:iframe-height option - or dynamically calculated using
playwright and a headless browser. To use the dynamic height calculation, you must install
the html dependency set:
pip install sphinxcontrib-typer[html]
The chromium browser is downloaded automatically the first time it is needed unless
typer_playwright_install is disabled.
Otherwise provide the typer:iframe-height option. Use typer:preferred html to
render the html output
.. typer:: examples.example:app
:preferred: html
:width: 65
:iframe-height: 300
Generate Nice PDFs¶
By default the latex builder will convert the preferred rendering output to pdf. This may not render predictably if the necessary fonts are not installed. You will likely need to install FiraCode. You will also need to install the pdf dependency set:
pip install sphinxcontrib-typer[pdf]
Alternatively you can convert the rendered helps to png format using the
typer:convert-png option and passing it the builders you want to render pngs. You will
also need to install the png dependency set:
pip install sphinxcontrib-typer[png]
Any format can be converted to png - even text!
.. typer:: examples.example:app
:preferred: text
:width: 90
.. typer:: examples.example:app
:preferred: text
:width: 90
:convert-png: latex|html
Usage: example [OPTIONS] {arg}:<one|two> COMMAND [ARGS]...
This is the callback function.
╭─ Arguments ─────────────────────────────────────────────────────────────╮
│ * arg <one|two> An argument. [required] │
╰─────────────────────────────────────────────────────────────────────────╯
╭─ Options ───────────────────────────────────────────────────────────────╮
│ --flag --no-flag Flagged. [default: no-flag] │
│ --switch -s Switch. │
│ --help Show this message and exit. │
╰─────────────────────────────────────────────────────────────────────────╯
╭─ Commands ──────────────────────────────────────────────────────────────╮
│ foo This is the foo command. │
│ bar This is the bar command. │
╰─────────────────────────────────────────────────────────────────────────╯
latexpdf often has issues with unicode characters.
You may get better results using the xeLaTeX engine instead, especially when rendering text.
In your conf.py add:
latex_engine = "xelatex"
Customize the Rendered Output¶
The initialization parameters for the rich console and export
functions can be overridden to provide more fine grained control over the rendered output. For
example, to render a console that looks like Red Sands on OSX we can use the
typer:svg-kwargs option, and pass an import string to a dictionary of kwargs to pass to
rich.console.export_svg().
1from rich.terminal_theme import TerminalTheme
2
3red_sands = {
4 'theme': TerminalTheme(
5 (132, 42, 38), # background
6 (210, 193, 159), # text
7 [
8 (210, 193, 159), #
9 ( 0, 0, 0), # required
10 ( 77, 218, 77), # option on short name
11 (227, 189, 57), # Usage/metavar
12 (210, 193, 159), #
13 ( 0, 18, 140), # option off
14 ( 75, 214, 225), # option on/command names
15 (210, 193, 159), #
16 ]
17 )
18}
.. typer:: examples.example:app
:width: 60
:preferred: svg
:svg-kwargs: examples.themes.red_sands
The preset Console parameters can also be overridden using the typer:console-kwargs
option. Refer to the rich documentation for more information on the available
options.
Render for Light and Dark Modes¶
Many Sphinx themes (Furo, pydata-sphinx-theme, sphinx-book-theme) let the reader switch between
light and dark modes in the browser. Since the mode is chosen at view time it cannot be detected
when the documentation is built, instead the help can be rendered once for each mode using the
typer:dark-theme option. Only the rendering that matches the active mode is shown:
.. typer:: examples.example:app
:theme: light
:dark-theme: dark
Note
If your html_theme is one that is known to support light and dark modes (currently
furo, pydata_sphinx_theme and sphinx_book_theme) this happens automatically: the
default value of typer_dark_theme is "auto" which resolves to "dark" for
those themes, so you do not need to do anything.
Any of the named themes may be used for either mode. To use a different dark
theme, or to enable dual rendering for a theme that is not recognized automatically, set
typer_dark_theme in conf.py rather than repeating the option on every directive.
Set it to None to switch dual rendering off:
typer_dark_theme = "monokai"
This works for both the svg and html (iframe) render targets. Themes that do not define the
only-light and only-dark classes are covered by a small stylesheet installed by the
extension that follows the data-theme attribute and the browser’s color scheme preference.
Builders other than html render the primary typer:theme only.
Cross-Referencing Commands¶
Every command rendered by the typer directive can be cross referenced using the
:typer: role. When the typer:make-sections option is used the reference links to
the generated section, otherwise it links to the rendered help output. For example, to
reference the example bar subcommand from the Render Subcommand Structure section above:
:typer:`example-bar`
The format for the reference is prog(-subcommand)
Use from Markdown¶
If your documentation is written in Markdown using MyST, the typer directive and role are
available with MyST’s directive and role syntax. The directive options are given as :option:
lines at the top of the fence:
```{typer} examples.example:app
:prog: example
:width: 65
:show-nested:
:make-sections:
```
The colon fence form works as well if you have enabled the colon_fence extension in
myst_enable_extensions:
:::{typer} examples.example:app:bar
:prog: example bar
:::
Cross references use the MyST role syntax, with the same target formats and optional link text
as the :typer: role:
See {typer}`example-bar` or {typer}`the bar subcommand <example-bar>`.