VersionΒΆ
Click Extra provides its own version option which, compared to Clickβs built-in:
adds new variable to compose your version string
adds colors
adds an environment summary for bug reports
works with standalone scripts
expose metadata in the context
DefaultsΒΆ
Here is how the defaults looks like:
import click
import click_extra
@click.command
@click_extra.version_option(fields={"version": "1.2.3"})
def cli():
pass
$ cli --help
Usage: cli [OPTIONS]
Options:
--version Show the version and exit.
--help Show this message and exit.
The default version message is the same as Clickβs default, but colored:
$ cli --version
cli, version 1.2.3
Hint
In the examples of this page the version is hard-coded to 1.2.3 for the sake of demonstration.
Without a hard-coded value, the version is fetched from the package metadata of the CLI or the __version__ attribute of the command.
Note
For drop-in compatibility with Click, the version can also be passed as the first positional argument: @version_option("1.2.3") is shorthand for @version_option(fields={"version": "1.2.3"}). A positional value starting with - is treated as a custom flag name instead, like every other option decorator.
VariablesΒΆ
The message template is a format string, which defaults to:
f"{prog_name}, version {version}"
Caution
This is different from Click, which uses the %(prog)s, version %(version)s template.
Click is based on old-school printf-style formatting, which relies on variables of the %(variable)s form.
Click Extra uses modern format string syntax, with variables of the {variable} form, to provide a more flexible and powerful templating.
You can customize the message template with the following variables:
Variable |
Description |
|---|---|
The module object in which the command is implemented. |
|
The |
|
The full path of the file in which the command is implemented. |
|
The string found in the local |
|
The name of the package in which the CLI is distributed. |
|
The version from the package metadata in which the CLI is distributed. |
|
The package author(s) from the core metadata, or |
|
The package license from the core metadata: SPDX |
|
User-friendly name of the executed CLI. Returns |
|
Version of the CLI. Returns |
|
The full path to the Git repository root directory, or |
|
The current Git branch name, or |
|
The full Git commit hash of the current |
|
The short Git commit hash of the current |
|
The commit date of the current |
|
The Git tag pointing at |
|
The full commit SHA that the current tag points at, or |
|
The number of commits since the most recent tag, or |
|
The work-tree state: |
|
When the distribution was built, as an RFC 3339 UTC timestamp, or |
|
The operating system the build ran on, or |
|
The platform a distribution built there installs on ( |
|
The CPU architecture the build ran on, or |
|
The display name of the program. Defaults to Clickβs |
Note
The git_* variables are evaluated at runtime by calling git. They return None in environments where Git is not available (like standalone Nuitka binaries or Docker containers without Git).
All git_* fields can be pre-baked at build time by defining __<field>__ dunder variables in the CLI module, or in the __init__.py of its package. Pre-baked values take priority over subprocess calls.
The hash, date, branch, tag and distance fields also fall back to a .git_archival.json file, so they keep working when a CLI runs from a git archive export (like a GitHub source tarball) that has no .git directory. The two hash fields then fall back to the commit recorded for a CLI installed from a Git URL.
Hint
The {version} variable is resolved in this order:
A
__version__variable defined alongside your CLI (see standalone scripts).A
__version__variable in the parent packageβs__init__.py, for a CLI that sits in a sibling module (like a__main__entry point, or the CLI of a compiled binary).The version from package metadata via
importlib.metadata: this is the most common source for installed packages.Noneif none of the above succeeds (like unpackaged scripts without__version__).
Both {exec_name} and {version} are derived through a short fallback chain ({version} additionally appends the Git short hash for .dev builds):
flowchart TD
subgraph EXEC["{exec_name}"]
direction TB
x1["{module_name}"] -->|"a __main__ entry point"| x2["{package_name}"]
x2 -->|"not packaged"| x3["script filename"]
end
subgraph VER["{version}"]
direction TB
m["{module_version}"] -->|unset| p["{package_version}"]
p -->|unset| nil["None"]
end
VER -.->|"if .dev without +local, and git available"| gh["append the Git short hash<br/>for example 1.2.3.dev0+abc1234"]
click EXEC "#click_extra.version.VersionOption.exec_name" "exec_name property"
click x1 "#click_extra.version.VersionOption.module_name" "module_name property"
click x2 "#click_extra.version.VersionOption.package_name" "package_name property"
click VER "#click_extra.version.VersionOption.version" "version property"
click m "#click_extra.version.VersionOption.module_version" "module_version property"
click p "#click_extra.version.VersionOption.package_version" "package_version property"
Error
Some Clickβs built-in variables are not recognized:
%(package)sshould be replaced by{package_name}%(prog)sshould be replaced by{prog_name}All other
%(variable)sshould be replaced by their{variable}counterpart
You can compose your own version string by passing the message argument:
import click
import click_extra
@click.command
@click_extra.version_option(
message="β¨ {prog_name} v{version} - {package_name}",
fields={"version": "1.2.3"},
)
def my_own_cli():
pass
$ my-own-cli --version
β¨ my-own-cli v1.2.3 - click_extra.sphinx
Caution
This result reports the package name as click_extra.sphinx because the example runs in the click-extra documentation build environment. This is a quirk of the documentation setup and does not affect your own CLI.
Overriding variables from the commandΒΆ
The version_fields parameter on @command and @group lets you override any template field without touching the default params list.
Fields can also be forced directly on the VersionOption instance via the params= argument:
import click
from click_extra import VersionOption
@click.command(params=[
VersionOption(
message="{prog_name} {version} (branch: {git_branch})",
fields={
"prog_name": "Acme CLI",
"version": "42.0",
"git_branch": "release/42",
},
),
])
def acme():
pass
$ acme --version
Acme CLI 42.0 (branch: release/42)
Standalone scriptΒΆ
The --version option works with standalone scripts.
Put this code in a file named greet.py:
greet.pyΒΆ 1#!/usr/bin/env -S uv run --script
2# /// script
3# dependencies = ["click-extra"]
4# ///
5
6import click_extra
7
8
9@click_extra.command
10def greet():
11 print("Hello world")
12
13
14if __name__ == "__main__":
15 greet()
Here is the result of the --version option:
$ greet --version
greet, version None
Because the script is not packaged, the {version} variable is None.
But Click Extra recognize the __version__ variable, to force it in your script:
greet.pyΒΆ 1#!/usr/bin/env -S uv run --script
2# /// script
3# dependencies = ["click-extra"]
4# ///
5
6import click_extra
7
8
9__version__ = "0.9.3-alpha"
10
11
12@click_extra.command
13def greet():
14 print("Hello world")
15
16
17if __name__ == "__main__":
18 greet()
$ greet --version
greet, version 0.9.3-alpha
Caution
The __version__ variable is not an enforced Python standard and more like a tradition.
It is supported by Click Extra as a convenience for script developers.
Development versionsΒΆ
When the version string contains .dev (as in PEP 440 development releases), Click Extra automatically appends the Git short commit hash as a PEP 440 local version identifier.
This lets you identify exactly which commit a development build was produced from:
import click
import click_extra
__version__ = "1.2.3.dev0"
@click.command
@click_extra.version_option()
def dev_cli():
pass
$ dev-cli --version
dev-cli, version 1.2.3.dev0+64a2d2f
For example, a version like 1.2.3.dev0 becomes 1.2.3.dev0+6e59c8c1 during development. Release versions (without .dev) are never modified.
If Git is not available or the CLI is not running from a Git repository, the plain .dev version is returned as-is.
Pre-baked versionsΒΆ
If the version string already contains a + (a PEP 440 local version identifier), Click Extra assumes the hash was pre-baked at build time and returns the version as-is, without appending a second hash.
This is useful for CI pipelines or Nuitka binaries where git is not available at runtime but the build step can inject the commit hash into __version__ before compilation:
import click
import click_extra
__version__ = "1.2.3.dev0+abc1234"
@click.command
@click_extra.version_option()
def prebaked_cli():
pass
$ prebaked-cli --version
prebaked-cli, version 1.2.3.dev0+abc1234
Hint
Click Extra ships prebake_version(), a utility to automate this injection. It parses a Python source file with ast, locates the __version__ assignment, and appends a +<local_version> suffix in place. Call it in your build step before Nuitka/PyInstaller compilation.
Version lifecycleΒΆ
The version resolution adapts to the runtime environment:
Scenario |
|
Git available? |
|
|---|---|---|---|
Local dev (from source) |
|
Yes |
|
Nuitka binary (pre-baked) |
|
No |
|
Nuitka binary (not pre-baked) |
|
No |
|
Release |
|
N/A |
|
For Nuitka binaries, the recommended workflow is to inject the commit hash into __version__ before compilation. The release workflow of Repomatic runs click-extra prebake all before compiling its binaries.
Pre-baking git metadataΒΆ
All git_* template fields support pre-baking. If the CLI module, or the __init__.py of its package, defines a __<field>__ dunder variable with a non-empty string value, that value is used instead of calling git at runtime. This is the recommended approach for compiled binaries (Nuitka, PyInstaller) where git is unavailable.
The supported dunders are:
Dunder variable |
Template field |
Subprocess fallback |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
To pre-bake a value, declare the dunder with an empty string placeholder in your __init__.py:
mypackage/__init__.pyΒΆ__version__ = "1.0.0.dev0"
__git_branch__ = ""
__git_short_hash__ = ""
Then inject values at build time using prebake_dunder():
from pathlib import Path
from click_extra.prebake import prebake_dunder
prebake_dunder(Path("mypackage/__init__.py"), "__git_branch__", "main")
prebake_dunder(Path("mypackage/__init__.py"), "__git_short_hash__", "abc1234")
prebake_dunder() only replaces empty strings, so running it twice is safe (idempotent). It preserves the quoting style and surrounding file content.
discover_package_init_files() can auto-discover __init__.py paths from the console scripts a project declares, in [project.scripts] of pyproject.toml or [options.entry_points] of setup.cfg, whether the package sits at the project root or under src/.
Pre-baking build metadataΒΆ
The build_* template fields answer a question the git_* ones cannot: which machine produced this binary, and when. A cross-built executable carries no trace of its build host, and env_summary() reports the machine running it, so the two describe different things and a bug report often needs both.
They are pre-baked exactly like the git fields, through the same empty-string dunders:
Dunder variable |
Template field |
Value baked at build time |
|---|---|---|
|
|
The build instant, as an RFC 3339 UTC timestamp |
|
|
The operating system the build ran on |
|
|
The wheel platform tag ( |
|
|
The CPU architecture the build ran on |
The column is titled differently from the git table on purpose: a git field falls back to a git subprocess when its dunder is empty, and a build field has no fallback at all. Nothing at runtime can recover the host that compiled a binary, so an unbaked build_* field stays None forever.
{build_target} is the one that states an ABI floor rather than a description. macosx-15.0-arm64 says the binary needs macOS 15, where {build_os} only says it was built on macOS.
Tip
__build_time__ reads SOURCE_DATE_EPOCH when the build sets it, so two runs of a reproducible build stamp the same instant instead of drifting apart. build_moment() is the function that resolves it, shared with the man pageβs own date stamp.
CLI usageΒΆ
The click-extra prebake command exposes these utilities from the command line, without writing Python:
$ # Bake __version__ and all git fields in one pass
$ click-extra prebake all
$ # Only inject Git hash into __version__
$ click-extra prebake version
$ click-extra prebake version --hash abc1234
$ # Set a specific field (double underscores added automatically)
$ click-extra prebake field git_tag_sha abc123def456...
$ click-extra prebake field git_branch main --module mypackage/__init__.py
All subcommands resolve the target file by precedence: an explicit --module, then the module key of the [tool.click-extra.prebake] configuration, then auto-discovery from the console scripts the project declares, in [project.scripts] of pyproject.toml or [options.entry_points] of setup.cfg. Pin the target once to drop --module from repeated build invocations:
[tool.click-extra.prebake]
module = "mypackage/__init__.py"
Git metadata in archivesΒΆ
The git_* variables normally shell out to git, so they go blank when a CLI runs from a tree that has no .git directory. The most common case is a source archive: the tar.gz GitHub generates for a tag, or any git archive export.
Git can bake the metadata into such archives at export time. Commit a .git_archival.json file holding git archive placeholders, and mark it for substitution in .gitattributes:
.git_archival.jsonΒΆ{
"node": "$Format:%H$",
"node-date": "$Format:%cI$",
"describe-name": "$Format:%(describe:tags=true,match=*[0-9]*)$",
"ref-names": "$Format:%D$"
}
.gitattributesΒΆ.git_archival.json export-subst
When git archive packs the file (GitHub does this for its source tarballs), it replaces each $Format:β¦$ token with the real value. Click Extra reads the result and populates {git_long_hash}, {git_short_hash}, {git_date}, {git_branch}, {git_tag}, {git_tag_sha} and {git_distance} from it. {git_dirty} is not covered: an archive has no work tree, so its state is unknowable.
Note
This is the schema used by setuptools-scm and Dunamai, so a single committed .git_archival.json works with all three.
Important
Substitution happens only inside git archive output. In a normal checkout the file still holds the literal $Format:β¦$ placeholders, which Click Extra ignores in favor of live git calls. The resolution order for each field is: pre-baked dunder, then live git, then .git_archival.json, then direct_url.json.
Commit of an install from a Git URLΒΆ
A CLI installed straight from a Git URL, like with uvx --from git+https://... or pip install git+https://..., runs from a wheel built out of a clone. That wheel holds no .git directory and no substituted .git_archival.json.
The installer records the commit it built in a direct_url.json file, beside the metadata of the distribution. Click Extra reads {git_long_hash} and {git_short_hash} from it, so the dev version of such an install still names its commit, as in 1.2.3.dev0+0123456. The other git_* fields stay empty: the record holds no date, and the revision it names can be a branch, a tag or a commit.
ColorsΒΆ
Each variable listed in the section above can be rendered in its own style. Pass a styles mapping to the version_option decorator to set the style of individual fields, keyed by field name:
styles={"version": Style(fg="green")}paints the{version}field green.styles={"version": None}clears the fieldβs style, so it falls back tomessage_style.
The message_style parameter sets the style of the message literals (the text around the fields) and of any field that has no style of its own. It defaults to None (no color).
Fields not listed in styles keep the defaults below, taken from VersionOption.default_styles. Fields absent from this table have no style of their own and fall back to message_style:
Field |
Default style |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
theme_slot() reads the style off the active theme each time the message renders, so these fields follow --theme. Under the default dark theme, invoked_command is bright white bold and success is green.
The remaining fields (module, module_file, author, license) have no default style and fall back to message_style.
Here is an example:
import click
from click_extra import version_option, Style
@click.command
@version_option(
message="{prog_name} v{version} π₯ {package_name} ( Ν‘ββ―ΝΚ Ν‘β)",
message_style=Style(fg="cyan"),
styles={
"prog_name": Style(fg="green", bold=True),
"version": Style(fg="bright_yellow", bg="red"),
"package_name": Style(fg="bright_blue", italic=True),
},
fields={"version": "1.2.3"},
)
def cli():
pass
$ cli --version
cli v1.2.3 π₯ click_extra.sphinx ( Ν‘ββ―ΝΚ Ν‘β)
Hint
You can pass None as a fieldβs style to disable styling for the corresponding variable, and set message_style=None to strip the style of the message literals:
import click
from click_extra import version_option
@click.command
@version_option(
message_style=None,
styles={"version": None, "prog_name": None},
fields={"version": "1.2.3"},
)
def cli():
pass
$ cli --version
cli, version 1.2.3
Environment informationΒΆ
env_summary() names the interpreter and the platform in one line, the two facts a bug report needs first. The platform also names the architecture of the machine when the interpreter has another one, like an x64 Python on Windows for ARM. That needs extra-platforms 15.0.0 or later. Add the line to the message of a plain --version:
import click
from click_extra import version_option
from click_extra.version_facts import env_summary
@click.command
@version_option(
message="{prog_name} {version} (" + env_summary() + ")",
fields={"version": "1.2.3"},
)
def weather():
pass
$ weather --version
weather 1.2.3 (Python 3.14.4, Ubuntu x86-64 (AMD64))
The message is a plain string, built when the decorator runs, so any other fact joins it the same way: from the standard libraryβs platform module, or from anywhere else. The version screen seats the same two facts beside a logo.
Todo
Drop the extra-platforms 15.0.0 caveat of this section once the floor of that dependency in pyproject.toml reaches it. platform_label() drops its getattr fallback at the same time.
Todo
Regroup the bug report helper of kdeldycke/meta-package-manager in Click Extra, so the project keeps only the content of its own reports, the override table:
Its
_build_issue_url()pre-fills the fields of an issue form from a user override, wherereport_form_url()fills the title alone.Its
override_experiment()suggests the override to test when the CLI cannot use a tool.
Version screenΒΆ
--version can draw a screen instead of a line: a logo, with the facts worth pasting into a bug report seated beside it. Click Extraβs own CLI does it, and the machinery is yours to point at any artwork.
VersionScreen owns the layout and nothing else. The mark arrives already rendered, as a string or the lines of one, so it can be ASCII line art, half-blocks, or whatever your renderer produces. Pass a callable returning either, and it runs when --version draws the screen:
from functools import partial
from click_extra import group
from click_extra.commands import default_params
from click_extra.version import VersionScreen
from click_extra.version_facts import default_facts
SCREEN = VersionScreen(
logo=" __ \n/\\_\\\n\\/_/",
tagline="A CLI of my own",
facts=lambda: default_facts() | {"Docs": "https://example.com"},
)
@group(params=partial(default_params, screen=SCREEN), version_fields={"version": "1.2.3"})
def my_cli():
pass
$ my-cli --version
__ my-cli, version 1.2.3
/\_\ A CLI of my own
\/_/
Python 3.14.4
Platform Ubuntu x86-64 (AMD64)
Docs https://example.com
Three things are worth knowing about that snippet.
The screen measures the logo; you never declare its size. Lines of unequal width are padded out to the widest, so a renderer that trims its own trailing blanks still lays out square. Repairing that afterwards is not something a caller can do anyway: str.ljust counts the escape sequences it cannot see, so on a styled line it does nothing at all.
Facts are an ordered mapping, so one row can be changed without restating the rest. dict keeps insertion order, and replacing a key leaves it where it sat:
default_facts() | {"Platform": my_own_label} # replaces, in place
default_facts() | {"Docs": DOCS_URL} # appends, at the end
default_facts() carries the interpreter and the platform. dependency_versions() is there for the Click and Cloup releases underneath you, opt-in rather than default. Labels get a column sized to the longest of them, separated from their values by the same gutter that separates the whole block from the logo.
Passing facts or logo a callable defers it to render time. Values that cost something to compute should be charged to the invocation that asks for --version, not to every invocation that might have: a plugin count, a registry probe, or a mark painted from its geometry.
When the screen is skippedΒΆ
Three conditions gate it, and failing any one falls back to the plain message template unchanged. That is a deliberate guarantee rather than a default: the plain form is the one every machine reader parses.
Color reaches the output. A flat-shaded mark carries its shape in the difference between its faces, and collapses into a single silhouette once the escapes are stripped. Color is also the one lever a caller already has: a redirected
--version, or one run under--no-colororNO_COLOR, is asking for something parseable.The terminal is wide enough to seat the facts beside the mark without wrapping them.
Accessible mode is off. A mark read out character by character is noise to a screen reader, so
--accessiblekeeps the plain message.
Click Extraβs own screenΒΆ
BRAND_SCREEN is the worked example: the six cubes of docs/assets/logo-square.svg, flat-shaded and painted with half blocks, two sub-pixels to a line. Its logo is the render_logo() callable, so the mark is painted when --version asks for it, not when the CLI starts.
$ click-extra --version
ββββββ
ββββββββ Click Extra, version 10.5.1.dev0+64a2d2f
ββββββββ Drop-in replacement for Click and Cloup
ββββββββββββββ
ββββββββββββββββ Python 3.14.4
ββββββββββββββββ Platform Ubuntu x86-64 (AMD64)
ββββββββββββββββββββββ Built on Click 8.5.1, Cloup 4.0.0
ββββββββββββββββββββββββ Docs https://kdeldycke.github.io/click-extra
ββββββββββββββββββββββββ
ββββββ ββββββ ββββββ
Hint
Two choices make the mark hold up where a copy of the artwork would not.
Its faces are flat and unoutlined, which is what lets one palette serve a light terminal and a dark one. An outlined mark carries its shape in the outline, so every stroke has to out-contrast the background, and the artworkβs own palette spans too wide a range for that: six of its colors vanish on white. A flat mark carries its shape in the difference between its three planes, which no background touches, leaving only the silhouette to keep its distance.
It is drawn in 2:1 dimetric rather than the artworkβs 30Β° isometric. A 30Β° edge advances 1.732 sub-pixels per row, which no grid can hold, so it comes out as a stair of alternating treads that reads as fraying at every size. Two across for every one down tiles a square grid exactly.
Debug logsΒΆ
When the DEBUG level is enabled, all available variables will be printed in the log:
import click
from click_extra import version_option, verbosity_option, echo
@click.command
@version_option(fields={"version": "1.2.3"})
@verbosity_option
def version_in_logs():
echo("Standard operation")
Which is great to see how each variable is populated and styled:
$ version-in-logs --verbosity DEBUG
debug: Set <Logger click_extra (DEBUG)> to DEBUG.
debug: Set <RootLogger root (DEBUG)> to DEBUG.
debug: 'click_extra.sphinx' package not found or not installed.
debug: Version string template variables:
debug: {module} : <module 'click_extra.sphinx.click_runner' from '/home/runner/work/click-extra/click-extra/click_extra/sphinx/click_runner.py'>
debug: {module_name} : click_extra.sphinx.click_runner
debug: {module_file} : /home/runner/work/click-extra/click-extra/click_extra/sphinx/click_runner.py
debug: {module_version} : 1.2.3.dev0+abc1234
debug: {package_name} : click_extra.sphinx
debug: 'click_extra.sphinx' package not found or not installed.
debug: {package_version} : None
debug: {author} : None
debug: {license} : None
debug: {exec_name} : click_extra.sphinx.click_runner
debug: {version} : 1.2.3
debug: {git_repo_path} : /home/runner/work/click-extra/click-extra
debug: {git_branch} : main
debug: {git_long_hash} : 64a2d2f51099e7479abeb8c095d68001685751b7
debug: {git_short_hash} : 64a2d2f
debug: {git_date} : 2026-12-06 14:52:38 +0400
debug: {git_tag} : None
debug: {git_tag_sha} : None
debug: {git_distance} : None
debug: {git_dirty} : clean
debug: {build_time} : None
debug: {build_os} : None
debug: {build_target} : None
debug: {build_target_arch}: None
debug: {prog_name} : version-in-logs
Standard operation
debug: Reset <RootLogger root (DEBUG)> to WARNING.
debug: Reset <Logger click_extra (DEBUG)> to WARNING.
Get metadata valuesΒΆ
You can get the uncolored, Python values used in the composition of the version message from the context:
import click
from click_extra import echo, pass_context, version_option
@click.command
@version_option(fields={"version": "1.2.3"})
@pass_context
def version_metadata(ctx):
version = ctx.meta["click_extra.version"]
package_name = ctx.meta["click_extra.package_name"]
prog_name = ctx.meta["click_extra.prog_name"]
echo(f"version = {version}")
echo(f"package_name = {package_name}")
echo(f"prog_name = {prog_name}")
$ version-metadata --version
version-metadata, version 1.2.3
$ version-metadata
version = 1.2.3
package_name = click_extra.sphinx
prog_name = version-metadata
Hint
These variables are presented in their original Python type: most are strings, module is the module object itself, and a field with nothing to report is None.
Note
Metadata values in ctx.meta are lazily evaluated: a field like git_long_hash is only computed the first time you access it. If your command only reads ctx.meta["click_extra.version"], the Git subprocess calls are never executed.
Template renderingΒΆ
You can render the version string manually by calling the optionβs internal methods:
import click
from click_extra import echo, pass_context, version_option, VersionOption, search_params
@click.command
@version_option(fields={"version": "1.2.3"})
@pass_context
def template_rendering(ctx):
# Search for a ``--version`` parameter.
version_opt = search_params(ctx.command.params, VersionOption)
version_string = version_opt.render_message()
echo(f"Version string ~> {version_string}")
Hint
To fetch the --version parameter defined on the command, we rely on click_extra.search_params.
$ template-rendering --version
template-rendering, version 1.2.3
$ template-rendering
Version string ~> template-rendering, version 1.2.3
That way you can collect the rendered version_string, as if it was printed to the terminal by a call to --version, and use it in your own way.
The other methods that build and render the version string are documented on the click_extra.version API page.