Argument Parents and Inheritance
When multiple commands share the same set of arguments (e.g., --verbose,
--format, --output), you can define them once in a parent command and
inherit them via add_parent(). This is equivalent to Python argparse’s
parents parameter.
Defining Shared Arguments
from argmojo import Command, Argument
def main() raises:
# Define shared arguments in a "parent" command.
# The name is arbitrary — it is never shown to users.
var shared = Command("_shared")
shared.add_argument(
Argument("verbose", help="Enable verbose output")
.long["verbose"]().short["v"]().flag()
)
shared.add_argument(
Argument("format", help="Output format")
.long["format"]().short["f"]()
.choice["json"]().choice["yaml"]().choice["csv"]()
.default["json"]()
)
# Inherit into multiple commands.
var cmd_a = Command("export", "Export data")
cmd_a.add_parent(shared)
cmd_a.add_argument(
Argument("path", help="Export path").positional().required()
)
var cmd_b = Command("report", "Generate report")
cmd_b.add_parent(shared)
cmd_b.add_argument(
Argument("title", help="Report title").long["title"]()
)
Both export and report now accept --verbose, -v, --format, and -f
without repeating their definitions.
What Gets Inherited
add_parent() copies:
- All arguments — flags, options, positionals, count flags, append, map, etc.
- Mutually exclusive groups —
mutually_exclusive() - Required-together groups —
required_together() - One-required groups —
one_required() - Conditional requirements —
required_if() - Implications —
implies()
All registration-time validation guards run on each inherited argument, so invalid combinations are caught immediately.
Multiple Parents
A command can inherit from multiple parents:
var io_args = Command("_io")
io_args.add_argument(
Argument("output", help="Output file").long["output"]().short["o"]()
)
var log_args = Command("_log")
log_args.add_argument(
Argument("verbose", help="Verbose").long["verbose"]().short["v"]().flag()
)
var cmd = Command("process", "Process data")
cmd.add_parent(io_args)
cmd.add_parent(log_args)
# cmd now has --output, -o, --verbose, -v
Using with Subcommands
Parent arguments can include .persistent() flags, which are then inherited by
the command and automatically propagated to its subcommands:
var global_args = Command("_global")
global_args.add_argument(
Argument("verbose", help="Verbose")
.long["verbose"]().short["v"]().flag().persistent()
)
var app = Command("app", "My app")
app.add_parent(global_args)
var sub = Command("run", "Run something")
sub.add_argument(Argument("target", help="Target").positional().required())
app.add_subcommand(sub^)
var result = app.parse()
# app -v run main → verbose=True, subcommand="run"
Notes
- The parent
Commandis not modified byadd_parent()— it can be shared safely across multiple children. - Child arguments added via
add_argument()coexist with inherited ones. - If you need different constraints for different children, apply them after
add_parent()on each child individually.