pallets/clickBSD-3-Clause06b2a67Report / request removal

Context and Execution

A Click Context is the per-invocation object that carries state relevant to script execution at each command level. It can hold user data, parameter defaults, parsing options, and nested-command relationships.

This object exists so Click can coordinate parsing, callbacks, nested commands, and cleanup without passing every internal detail through every callback. A context can also become the current context and can close resources when execution ends.

Sources: src/click/core.py:234-982, src/click/core.py:366-540, src/click/core.py:595-630

Core concepts

Context

A Context is the state container for one command invocation and may point to a parent context for a nested command.

Sources: src/click/core.py:234-982, src/click/core.py:366-540

Current context

The current context is the context at the top of Click’s local context stack, retrieved by get_current_context.

Sources: src/click/globals.py:20-41

Invocation state

Invocation state is the parsed values, remaining arguments, protected command tokens, defaults, and shared metadata stored across a context hierarchy.

Sources: src/click/core.py:366-540, src/click/core.py:633-658, src/click/core.py:1392-1426

Teardown

Teardown is the point where Click unwinds registered resources and close callbacks, usually when a context exits or close is called.

A context carries several kinds of state. The most important fields are these:

FieldPlain-language role
commandThe Command represented by this context.
parentThe enclosing context, or None at the top level.
paramsParsed parameter names and values.
argsRemaining arguments after parsing.
_protected_argsCommand tokens temporarily held back for nested parsing.
objUser data, inherited from the parent when not supplied.
default_mapA mapping that can provide parameter defaults.
invoked_subcommandThe subcommand name, None, or * for a chained group.

Sources: src/click/core.py:580-592, src/click/core.py:715-720, src/click/core.py:722-738, src/click/core.py:366-540

How a context carries invocation state

A command creates a context through make_context. That method copies values from the command’s context_settings, constructs the configured context_class, temporarily scopes the new context, and parses the argument list before returning the context.

The constructor establishes the parent-child relationship and initializes execution state. A child inherits obj from its parent when no object is supplied, while a nested default_map can be selected from the parent using the child’s info_name.

Parameter parsing moves values into ctx.params and leaves unconsumed values in ctx.args. For groups, parsing separates the next subcommand token into ctx._protected_args; in chain mode, all command tokens remain protected until group invocation resolves them.

Parameter values retain their origin. get_parameter_source reports the recorded source, allowing callers to distinguish a command-line value from a default even when the values are equal.

Defaults are resolved through the context. lookup_default reads from default_map, and Parameter.get_default checks that context-level mapping before using the parameter’s local default.

ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)

with ctx.scope(cleanup=False):
    self.parse_args(ctx, args)
return ctx

The creation boundary is explicit: parsing runs inside a temporary scope, and the constructed context is returned afterward.

Sources: src/click/core.py:1355-1390, src/click/core.py:366-540, src/click/core.py:1392-1426, src/click/core.py:2034-2046, src/click/core.py:966-982, src/click/core.py:2586-2632, src/click/core.py:811-831, src/click/core.py:2550-2581

How Click finds the current context

Click avoids requiring every helper to receive ctx explicitly by maintaining a local stack. get_current_context returns the last item in _local.stack; if no context is available, it raises RuntimeError unless silent=True.

scope makes a context current by entering it as a context manager. Its default behavior includes cleanup, while cleanup=False increments a depth counter so a temporary nested push can defer cleanup.

This supports both explicit and implicit access. The pass_context decorator calls get_current_context and supplies the result as the callback’s first argument, while helpers can call get_current_context directly.

The shared meta dictionary is another form of cross-context state. Nested contexts share it so Click utilities can store state there, with namespaced keys recommended by the implementation.

Context state and lookup — How does execution state become available to nested helpers?

Evidence

The diagram separates explicit context flow from implicit lookup: command code creates and scopes the context, while helpers read the top stack entry instead of receiving the object through every call.

Sources: src/click/globals.py:20-41, src/click/core.py:595-630, src/click/decorators.py:28-36, src/click/core.py:633-658, src/click/core.py:1355-1390

How invocation and teardown proceed

At the application boundary, Command.main creates a context, invokes the command, and, in standalone mode, exits after invocation. The context is entered with with, so its teardown runs as that block leaves.

Command.invoke delegates callback execution through ctx.invoke. When invoking a command object, Click creates a subcontext, fills missing exposed parameters with defaults, records keyword arguments in ctx.params, and calls the callback inside augment_usage_errors.

Groups extend this flow by resolving subcommands and creating child contexts. In non-chain mode, the group context is entered first, the subcommand is resolved, and the child context is then created and invoked; in chain mode, Click creates child contexts step by step and invokes each one.

One command invocation — What call order carries a command from arguments to callback and cleanup?

Evidence

The sequence separates parsing from callback execution: make_context parses first, invoke dispatches second, and context teardown closes resources afterward.

Sources: src/click/core.py:1511-1645, src/click/core.py:883-936, src/click/core.py:1428-1442, src/click/core.py:2048-2114, src/click/core.py:1355-1390, src/click/core.py:722-738

How resources are closed

A context-manager exit decrements the context depth. When the depth reaches zero, __exit__ calls _close_with_exception_info; pop_context then runs on every __exit__ call.

close invokes the exit stack, which runs callbacks registered through call_on_close and exits context managers entered through with_resource. The exit stack receives exception information and is replaced afterward so the context can be reused.

with_resource enters a context manager immediately and arranges for its __exit__ method to run when the context is popped. call_on_close registers a function to execute during teardown.

Calling exit closes the context before raising Exit, so explicit application termination performs registered cleanup first.

Context lifecycle — How does a Context move from creation to cleanup?

Evidence

The important lifecycle rule is depth sensitivity: nested scopes defer exit-stack cleanup until the outermost scope reaches zero, while explicit close or exit drives cleanup directly.

Sources: src/click/core.py:580-592, src/click/core.py:715-720, src/click/core.py:722-738, src/click/core.py:674-701, src/click/core.py:703-713, src/click/core.py:845-853, src/click/core.py:595-630

How it connects

Commands and groups create the contexts used for parsing and dispatch; read Commands and Groups for the command hierarchy and subcommand flow.

Parameters use the context to resolve defaults, environment values, type conversions, and parameter sources; read The Parameter Model for that value-resolution path.

Decorators provide callback-facing entry points, including pass_context; read The Decorator API for how functions become Click commands and receive context-derived values.

The broader execution model starts at Click Overview, while in-process command execution is covered by Testing with CliRunner.

Sources: src/click/core.py:2048-2114, src/click/core.py:2550-2581, src/click/core.py:2586-2632, src/click/core.py:2708-2772, src/click/decorators.py:28-36, src/click/core.py:1511-1645

Key takeaways

  • Context carries command identity, parentage, parsed values, remaining arguments, defaults, user data, and execution metadata.
  • get_current_context finds the top context from Click’s local stack.
  • make_context parses arguments; invoke performs callback dispatch.
  • __exit__ closes resources only at depth zero, but always pops the current context.
  • close, with_resource, call_on_close, and exit coordinate teardown.

Want this for your repos?

Try Angada AI Wiki