Introducing typer-scion: inherit CLI options in subcommands
TLDR
typer-scion lets typer subcommands use options defined by their parent command. Mark an option with
Inheritable() and decorate subcommands with @inherit to receive it.
The typer library makes it a breeze to build a command-line application from ordinary Python functions. After years of
using it for my own CLI apps, though, one point has caused me a lot of irritation. Because it relies on click, it
doesn't do a great job with "interspersed options." That is, if a parent command takes an option, there's not a good
way to let you pass that option through a subcommand.
For example, I usually have a global verbosity flag to make the CLI produce debug output as it operates. I usually have the main callback function for the app accept this option. That means, to enable verbose output, I have to pass that option to the root command like so:
Many CLI apps you encounter out in the world allow you to pass root-level options after the subcommands, and this
feels quite natural. That's especially true if you have a relatively complex command to re-issue with only the output
verbosity changed. Ideally, you just hit the up-arrow key and add a --verbose to the end of the last command
This doesn't work with typer out of the box, and there hasn't been a good way to do this without:
- hacky workarounds
- duplicating the options on all subcommands hooking back into the parent callback logic
- just giving up and accepting the mild irritation
typer-scion solves the problem in an ergonomic and explicit manner. The parent callback still owns the option, but a
child subcommand can opt into "inheriting" the parent option.
The scenario
Suppose I'm building an app named archivist for tracing genealogies through long-generations of the ancient noble
houses. The root archivist command owns the --verbose flag that turns on extra genealogy records. Using
typer-scion, I can make that flag "inheritable" in subcommands.
Consider this command tree:
If I mark --verbose as Inheritable() on archivist, then the lineage subcommand can accept it as an option and
pass it back to the root callback:
import logging
from typing import Annotated
import typer
from typer_scion import Inheritable, Inherited, inherit
app = typer.Typer()
house = typer.Typer()
@app.callback()
def main(verbose: Annotated[bool, typer.Option(help="Enable debug logging."), Inheritable()] = False):
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
@house.command()
@inherit
def lineage(verbose: Annotated[bool, Inherited()]):
logging.info("Reading the Atreides lineage")
if verbose:
logging.debug("Verbose genealogy records are enabled")
app.add_typer(house, name="house")
The same command now accepts --verbose in any of these positions:
archivist --verbose house lineage
archivist house --verbose lineage
archivist house lineage --verbose
The inherited option also appears in the leaf command's help output:
$ archivist house lineage --help
Usage: archivist house lineage [OPTIONS]
Options:
--help Show this message and exit.
Inherited from main:
--verbose Enable debug logging.
The root callback sees the value regardless of which ordering the user chooses, so it can configure logging before the command body runs.
Installation
Install typer-scion alongside Typer with uv:
Or install it with pip:
The package supports Python 3.12 through 3.15. Outside of the explicit Inheritable() and @inherit declarations,
typer-scion leaves Typer alone. Your applications, callbacks, commands, parameters, and help text can carry on as
usual.
Going a little deeper
Let's go back to our example archivist app. It's a perfectly ordinary typer application. The only unusual bit is
Inheritable(), which rides along with the existing option through Annotated:
import logging
import sys
from typing import Annotated
import typer
from typer_scion import Inheritable, Inherited, inherit
app = typer.Typer()
log = logging.getLogger("archivist")
@app.callback()
def main(verbose: Annotated[bool, typer.Option(help="Log at DEBUG instead of INFO."), Inheritable(), ] = False):
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(level=level, format="[%(levelname)s] %(message)s", stream=sys.stdout, force=True)
So far, this is still just a normal root option. Inheritable() simply makes verbose available for subcommands that
opt in. The original root-level command spelling still works:
Next, we'll add a little magic to let a subcommand inherit the parent callback's option. The @inherit decorator is
enough to opt the command into the inheritance chain:
house = typer.Typer()
@house.command()
@inherit
def lineage():
log.info("Reading entire lineage")
log.debug("Loading ancestors, descendants, and disputed claims")
app.add_typer(house, name="house")
Since @inherit handles the CLI plumbing, the lineage subcommand can now accept the --verbose flag and pass it back
to the parent callback.
And, to stay flexible, it works before the subcommand too:
The lineage subcommand's help includes --verbose in an Inherited from ... section. The option keeps the definition
from the parent, so there is one source of truth for its CLI behavior.
Why the root callback runs again
Normally, typer runs the root callback before it parses the lineage command. That means it would miss
--verbose when the option appears at the end of archivist house lineage --verbose.
typer-scion runs the root callback again with the child's value. The root can then switch logging to DEBUG before
lineage does any work. Because the root callback may run twice, it should be safe to run twice.
Logging setup is fine here: configuring it again is harmless. A callback that creates duplicate files, sends notifications, or charges a credit card would be a much worse candidate.
Receiving inherited options
So far, @inherit has handled the plumbing without putting verbose in the function signature. When the inheriting
subcommand needs the actual value, Inherited() is the explicit form: it says the parameter comes from an ancestor and
should use that ancestor's option definition.
Here, verbose arrives in the function as a normal Boolean. The command can inspect it, pass it onward, or use it to
change its own behavior:
@house.command()
@inherit
def status(verbose: Annotated[bool, Inherited()]):
if verbose:
log.debug("The archivist is reading the full genealogy record")
log.info("Reporting lineage status")
A command can also collect every inherited value through **kwargs:
@house.command()
@inherit
def status(**shared: Any):
if shared.get("verbose"):
log.debug("The archivist is reading the full genealogy record")
log.info("Reporting lineage status")
This works well for a command that forwards shared configuration to another layer or wants to handle a variable set of
options. typer-scion adds the inherited options to the command's CLI even though they do not appear as named
parameters.
If you do not want to access inherited values through the function signature, you can explicitly call the
get_inherited() command instead:
from typer_scion import get_inherited
@house.command()
@inherit
def status():
shared = get_inherited()
if shared.get("verbose"):
log.debug("The archivist is reading the full genealogy record")
log.info("Reporting lineage status")
The three forms solve different readability problems:
| Form | Best for |
|---|---|
Inherited() |
A command needs a specific shared option as a typed parameter |
**kwargs |
A command accepts all shared options as a collection |
get_inherited() |
Shared values belong to command implementation logic, not its signature |
Multiple levels of nesting
Suppose we need to add in some deeper heirarchies to make our archivist program handle variations at different levels.
For, example, the house group chooses whose lineage we're working with, the lineage group sets the search depth, and
the final command lists the ancestors.
app = typer.Typer()
house = typer.Typer()
lineage = typer.Typer()
@app.callback()
def root(verbose: Annotated[bool, typer.Option(), Inheritable()] = False):
...
@house.callback()
@inherit
def house_options(
verbose: Annotated[bool, Inherited()],
house_name: Annotated[str, typer.Option(help="Noble house to inspect."), Inheritable()] = "Atreides",
):
...
@lineage.callback()
@inherit
def lineage_options(
house_name: Annotated[str, Inherited()],
depth: Annotated[int, typer.Option(help="Generations to include."), Inheritable()] = 3):
...
@lineage.command()
@inherit
def ancestors(
depth: Annotated[int, Inherited()],
house_name: Annotated[str, Inherited()],
verbose: Annotated[bool, Inherited()],
):
print(f"house={house_name} depth={depth} verbose={verbose}")
house.add_typer(lineage, name="lineage")
app.add_typer(house, name="house")
Every intermediate callback that should pass options farther down the tree needs @inherit. The resulting command can
configure the house, search depth, and logging in one go:
A group without a callback contributes nothing, so the search continues with its parent. A callback without @inherit
ends the chain. It can share its own options, but options from groups above it do not pass through.
A command can shadow an inherited option
A command may need a local interpretation of an option with the same name. Its own parameter takes precedence over the inherited option. For example, a quick lineage query can deliberately override the lineage group's default:
@house.command()
@inherit
def generations(
verbose: Annotated[bool, Inherited()],
depth: int = 1,
):
print(f"verbose={verbose} generation_depth={depth}")
If the parent also shares depth, generations keeps its own declaration and default of 1. The remaining inherited
options are still available. The closer declaration wins, like a local lineage plan overriding a house-wide preference.
What errors look like
typer-scion validates the relationship between the declarations instead of silently producing a partly working CLI.
Its configuration errors derive from ScionError, so callers can catch the whole family or a specific subclass.
An Inherited() parameter must match an option shared by an ancestor:
If no ancestor marks depth with Inheritable(), typer-scion raises UnknownInheritedOptionError.
An inherited parameter cannot declare its own default. The parent owns that definition:
This raises InheritedDefaultError. Move the default to the parent callback instead.
Finally, Inheritable() belongs on group callbacks. A command's options cannot flow to sibling commands, so marking a
command option as inheritable raises InheritableOnCommandError.
These errors catch the three common mistakes early:
- asking for a name that no ancestor shares;
- duplicating the parent's default in the child; and
- trying to share an option from a command rather than a callback.
Run the complete demo
The package includes a demo that walks through the examples in an isolated environment:
Use --help to see the available demonstrations. The source repository also includes complete scripts for the basic
case, nested groups, and error handling in its
examples directory.
Try it in your own CLI
typer-scion gives you the ability to use "interspersed options" in your CLI apps. Option ownership is keptsimple. A
parent callback defines its options and marks them as Inheritable() as needed. Then, each command specifies if it can
accept options that belong to its ancestors.
The API is small and exlicit:
Inheritable()marks a parent option as shareable.@inheritopts a command or intermediate callback into the inheritance chain.Inherited()allows a subcommand to access its ancestor's option value.
The demo is a good starting point to see typer-scion in action, but you'll learn even more if try this in one of your
existing CLI apps:
- Find one global option, such as
--verbose,--config, or--profile. - Mark it with
Inheritable()on the parent callback. - Add
@inheritto one command that would benefit from accepting it at the end of the command line.
That's it! If the experiment exposes an edge case, the typer-scion issue tracker is the place to share it.
Thanks for reading, and I look forward to any feedback you might have!
