Context

Click Extra’s option callbacks publish their resolved values on Click’s Context.meta dict. That dict is shared across the parent/child context hierarchy and lives for the duration of a single CLI invocation, so it doubles as a per-request shared bus between Click Extra’s eager callbacks and your own command body.

If you are writing a @command- or @group-decorated function, you can read any of the entries below at any point: in the function body, in a parameter callback, in a @pass_context consumer, or in a subcommand of a group that declared one of the options. Click Extra’s default options (--verbosity, --theme, --config, --time, etc.) are wired in automatically by @command / @group, so their callbacks write the corresponding entries.

Picking values up from your own callbacks

Every key Click Extra owns lives under the click_extra. namespace and is exposed as a constant in the click_extra.context module:

from click_extra import command, context, echo, pass_context

@command
@pass_context
def status(ctx):
    """Print a status line tagged with the current verbosity."""
    level = ctx.meta[context.VERBOSITY_LEVEL]
    echo(f"[{level}] all systems nominal.")
$ status --verbosity INFO
[INFO] all systems nominal.

You may also reach the same entry through the literal string (ctx.meta["click_extra.verbosity_level"]): the constants only fix the spelling in one place and document who owns each entry.

Available keys

The table below lists every entry Click Extra publishes for your code, the option that triggers it, and the value’s shape. Entries marked write-only are not read back internally: they exist so your code can inspect what the user picked.

Constant

String key

Set by

Value

context.RAW_ARGS

click_extra.raw_args

Command.make_context (always, on @command and @group)

list[str]: pre-parsed argv slice fed to the current command

context.INVOCATION_NAME

click_extra.invocation_name

Command.make_context (root context only)

str: the name the CLI was invoked under (write-only)

context.CONF_SOURCE

click_extra.conf_source

ConfigOption.load_conf (@config_option)

pathlib.Path | str | None: file or URL the configuration came from

context.CONF_FULL

click_extra.conf_full

ConfigOption.load_conf (@config_option)

dict | None: full parsed configuration document

context.CONF_SOURCES

click_extra.conf_sources

ConfigOption.load_conf (@config_option)

tuple[(path, dict), ...]: every loaded file, highest precedence first

context.TOOL_CONFIG

click_extra.tool_config

ConfigOption.load_conf (with config_schema)

The deserialised app section (also reachable via get_tool_config())

context.VERBOSITY_LEVEL

click_extra.verbosity_level

--verbosity, -v, -q, --debug callbacks (reconciled)

LogLevel: the level every verbosity option settled on

context.VERBOSITY

click_extra.verbosity

--verbosity callback

LogLevel: raw value of --verbosity LEVEL

context.DEBUG

click_extra.debug

--debug callback

bool: True when --debug was passed, absent otherwise

context.VERBOSE

click_extra.verbose

--verbose / -v callback

int: repetition count

context.QUIET

click_extra.quiet

--quiet / -q callback

int: repetition count

context.START_TIME

click_extra.start_time

--time callback (@timer_option)

float: time.perf_counter() snapshot

context.JOBS

click_extra.jobs

--jobs callback (@jobs_option)

int: effective parallel job count (clamped to >= 1)

context.PROGRESS

click_extra.progress

ProgressOption.set_progress (always present on @command)

bool: True when progress spinners may display

context.ACCESSIBLE

click_extra.accessible

--accessible callback (always present on @command)

bool: True when the user asked for screen-reader-friendly output

context.TABLE_FORMAT

click_extra.table_format

--table-format callback (@table_format_option)

TableFormat

context.SORT_BY

click_extra.sort_by

--sort-by callback (@sort_by_option)

tuple[str, ...]: column IDs in priority order

context.TABLE_SORT_KEY

click_extra.table_sort_key

--sort-by callback (@sort_by_option, column definitions)

Callable: row sort key, absent when only bare column IDs are given

context.COLUMNS

click_extra.columns

--columns callback (@columns_option)

tuple[str, ...]: column IDs in display order (empty: every column)

context.THEME

click_extra.theme.active

--theme callback (always present on @command)

HelpTheme: palette picked for this invocation

context.THEME_OVERRIDES

click_extra.theme.overrides

ConfigOption ([tool.<cli>.themes.<name>] tables)

dict[str, HelpTheme]: themes declared in the configuration file

context.TELEMETRY

click_extra.telemetry

--telemetry callback (@telemetry_option)

bool: True if the user opted into telemetry (write-only)

context.ZERO_EXIT

click_extra.zero_exit

-0 / --zero-exit callback (@zero_exit_option)

bool: True to always exit 0 (write-only)

Click Extra keeps a few more entries for its own bookkeeping, and leaves them out. One example is context.SUBCOMMANDS_APPLIED, which stops a group from applying its reserved subcommand keys twice. The --version option also publishes each of its template fields as click_extra.<field>: see Get metadata values.

Worked examples

Switching behavior on the active theme

from click_extra import command, context, echo, pass_context

@command
@pass_context
def report(ctx):
    """Render a status line in the active theme's success colour."""
    theme = ctx.meta[context.THEME]
    echo(theme.success("OK"))
$ report --theme dark
OK

Driving parallelism off --jobs

--jobs is not part of the default options, so it has to be added explicitly via @jobs_option:

from click_extra import command, context, echo, jobs_option, pass_context

@command
@jobs_option
@pass_context
def crunch(ctx):
    """Demonstrate reading the resolved `--jobs` value."""
    echo(f"Working with {ctx.meta[context.JOBS]} workers.")
$ crunch --jobs 4
Working with 4 workers.

Inspecting the loaded configuration

--config is part of the default options. The block below uses --no-config to skip discovery, then reads CONF_SOURCE to confirm no file was loaded:

from click_extra import command, context, echo, pass_context

@command
@pass_context
def show_conf(ctx):
    """Print which configuration file (if any) was loaded."""
    source = ctx.meta.get(context.CONF_SOURCE)
    echo(f"config: {source or 'none'}")
$ show-conf --no-config
Skip configuration file loading altogether.
config: none

Reaching the context outside the command body

Inside a @command-decorated function, you can either accept ctx via @pass_context or call click.get_current_context() from any helper that runs while the CLI is being invoked. Both give you the same context, and both expose the same .meta dict.

Caution

Outside an active CLI invocation (for example at import time, in unit tests that build options directly without invoking a CLI, or in a REPL) there is no context, and these keys are not available. Helpers that need to work in both modes should fall through to a sane default. The theming layer does this with get_current_theme(), which falls back to get_default_theme() when no context is in flight.

POSIX-compliant argument parsing

Click’s default parser lets options and positional arguments interleave freely (GNU style): mytool alice --greeting Hi bob is parsed the same as mytool --greeting Hi alice bob. The POSIX convention is stricter: option parsing stops at the first positional argument, and everything after it is treated as a positional, even tokens that look like options.

Context honors the standard POSIXLY_CORRECT environment variable that GNU getopt-based tools obey. When it is present in the environment (regardless of its value), Click Extra forces allow_interspersed_args to False, so any @command or @group built with Click Extra automatically switches to POSIX parsing.

from click_extra import argument, command, echo, option

@command
@option("--greeting", default="Hello")
@argument("names", nargs=-1)
def greet(greeting, names):
    """Greet each name with the chosen greeting."""
    for name in names:
        echo(f"{greeting}, {name}!")

By default, the --greeting option is picked up wherever it appears on the line:

$ greet alice --greeting Hi bob
Hi, alice!
Hi, bob!

With POSIXLY_CORRECT set, the first positional (alice) ends option parsing, so --greeting keeps its default and the remaining tokens collapse into the names argument:

$ POSIXLY_CORRECT=1 greet alice --greeting Hi bob
Hello, alice!
Hello, --greeting!
Hello, Hi!
Hello, bob!

This applies per command, so a group and each of its subcommands independently switch to POSIX parsing when the variable is set. Because presence alone is enough, POSIXLY_CORRECT also overrides an explicit context_settings={"allow_interspersed_args": True}: it can only make parsing stricter, never re-enable interspersing.