/cyclopts:cycloptsfrom cyclopts
Cyclopts patterns and pitfalls for Python CLIs. Cyclopts looks like Typer but parses differently, so Typer muscle memory is subtly wrong. Use when writing or editing code that imports `cyclopts`, or when the user mentions cyclopts.
Ships in cyclopts. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A type-hint-first CLI library. Looks like Typer but parses differently and has tighter typing. Most "Typer muscle memory" patterns are slightly wrong here, so read the patterns below before writing.
Docs root: https://cyclopts.readthedocs.io/en/latest/
Written for cyclopts 5 (Python ≥ 3.11), checked against 5.5.1. When touching a codebase pinned to v4, or upgrading one, read the "Migrating to v5" page in LINKS.md first.
src: Path, count: int = 1, tags: list[str] — cyclopts parses them. Reach for Annotated[T, Parameter(...)] only when you need to customize a specific field (flag name, env var, validator, negation knobs, group, …). Parameter is the unified replacement for Typer's Argument + Option.cyclopts.types before reaching for a raw validator. It has ~70 ready-made Annotated shortcuts (ExistingFile, PositiveInt, Port, Email, …); see the section below.__doc__ summary becomes the command description; entries inside a Parameters section (Numpy / Google / RST / Epytext, all supported) become per-parameter help, keyed by the Python variable name, not the CLI flag. App-level docstring works the same for the whole CLI. The docstring is the single source of help: it doubles as Python documentation and keeps the signature readable. Parameter(help=...) is for help-less callables (lambdas, partials, generated commands) or overriding a single inherited entry.verbose: bool → --verbose and --no-verbose; tags: list[str] → --tags and --empty-tags. Usually fine as-is. To change it: Parameter(negative="--quiet") renames, Parameter(negative="") disables — see Parameters.Parameter fields override per-field, not wholesale. If App.default_parameter sets name_transform and an Annotated sets validator, both apply. Priority chain (highest first): function Annotated → param's group → App.default_parameter → app's group → parent app.app() reads sys.argv[1:], dispatches to the matched function, then sys.exit()s: an int return is the exit code, False exits 1, a str is printed, anything else exits 0. Parse errors (unknown option, bad value) exit 2, like argparse and Click. Override with result_action="return_value" for tests/embedding.| You want… | Idiom |
|---|---|
Bool flag (auto-paired --no-X) | verbose: bool = False |
Counting flag (-vvv → 3) | Annotated[int, Parameter(count=True, alias="-v")] = 0 |
Rename the flag (drops auto --var-name) | Parameter(name="--my-flag") |
| Add a short alias (keeps auto name) | Parameter(alias="-f") |
| Env-var fallback | Parameter(env_var="MYAPP_X") |
| Hide from help | Parameter(show=False) |
| File that must exist | cyclopts.types.ExistingFile |
File or stdin/stdout (-) | cyclopts.types.StdioPath |
| Constrained number | cyclopts.types.Port / PositiveInt / PercentInt / NormFloat / Email / URL / Json |
Restrict a str to choices | Literal["json", "yaml"], or Parameter(choices=[...]) when the list is built at runtime |
Value placeholder in help (--config FILE) | Parameter(metavar="FILE") |
| Runtime shell completions (git branches, DB rows) | Parameter(completer=fn); fn(ctx) returns values or {value: description} |
| Short alias for the negative flag | Parameter(negative_alias="-D") (keeps --no-X) |
| Custom validator | Parameter(validator=fn_that_raises_AssertionError) |
| Subcommand | @app.command on a function |
| Nested subcommands | sub = App(name="db"); app.command(sub) |
| Flatten a sub-app's commands | app.command(sub, name="*") |
| Mutually exclusive flags | Group(validator=validators.MutuallyExclusive()) + Parameter(group=g) |
| Share params across commands | @dataclass + Annotated[Common, Parameter(name="*")] |
| Defaults from TOML / env / YAML / JSON | App(config=[config.Env(...), config.Toml(...)]) |
| Async command | App(backend="asyncio") + async def |
| Per-param help | docstring Parameters section (numpy / google / RST) |
| Test the app | app([...], result_action="return_value") |
Read args from a file (myapp @run.args) | App(argfile_prefix="@"); one argument per line, files may nest (≥ 5.4) |
| Lazy-load subcommand | app.command("pkg.module:func") |
| Self-installed shell completion | app.register_install_completion_command() |
from cyclopts import App
app = App(name="myapp", help="Demo CLI.")
@app.default # runs when no subcommand given. Functions only — not sub-Apps.
def main(name: str, count: int = 1, *, formal: bool = False):
"""Greet someone."""
@app.command # function name -> kebab-case: `my_func` -> `myapp my-func`
def my_func(): ...
@app.command(name="ship-it", alias="si", group="Admin")
def deploy(): ...
# Sub-app (nested commands):
db = App(name="db")
app.command(db) # `myapp db migrate`
@db.command
def migrate(): ...
# Flatten a sub-app so its commands hang off the parent. No other kwargs allowed when name="*".
app.command(tools_app, name="*")
if __name__ == "__main__":
app()
Behavior: myapp Alice → main("Alice"); myapp db migrate → migrate(); myapp (no args, but main needs name) → error + help. For a one-function script, skip App entirely: cyclopts.run(main).
Async commands are first-class. Set App(backend="asyncio") (or "trio") and decorate async def directly — cyclopts drives the loop. Per-call override: app(backend="trio"). There's also App.run_async() if you want to await it yourself.
The example below deliberately shows several customizations side-by-side; real code has far fewer:
from pathlib import Path
from typing import Annotated
from cyclopts import App, Parameter
from cyclopts.types import ExistingFile
app = App()
@app.command
def convert(
src: ExistingFile, # validator baked in via cyclopts.types
n: Annotated[int, Parameter(name=["--count", "-n"])] = 1, # rename + short flag
tag: Annotated[str, Parameter(alias="-t", env_var="MYAPP_TAG")] = "",
verbose: Annotated[bool, Parameter(negative="--quiet")] = False, # rename the auto-pair: --verbose / --quiet
):
"""Convert a file.
Parameters
----------
src
Source file (must exist).
n
Repeat count.
tag
Free-form tag, also read from MYAPP_TAG.
verbose
Enable verbose output.
"""
Changing auto-negation:
Parameter(negative="--quiet") # rename: --verbose / --quiet
Parameter(negative_bool="dont-") # change the prefix: --verbose / --dont-verbose (default "no-")
Parameter(negative_iterable="clear-") # change iterable prefix (default "empty-")
Parameter(negative="") # disable: only --verbose
Also: negative_none (no default prefix) lets you generate a flag that sets an Optional[X] parameter back to None.
Counting flags (Parameter(count=True) on an int): short forms concatenate (-vvv == -v -v -v == 3), and no negative flag is generated.
Force --option=value syntax. Parameter(requires_equals=True) rejects the space form; useful for params whose value could itself look like a flag. Settable app-wide via App(default_parameter=Parameter(requires_equals=True)).
Parameter kwargs by frequency:
name (replace derived flag), alias (extra flag), env_var, negative / negative_bool / negative_iterable, negative_alias, group, validator, converter, choices, count (for -vvv).show, show_default, show_choices, show_env_var, metavar.completer.accepts_keys, allow_leading_hyphen, allow_repeating, consume_multiple, n_tokens, parse, requires_equals, json_dict, json_list.int accepts 0b…/0o…/0x…/decimal. float, complex via cast.bool keyword: --flag / --no-flag (auto-paired; configurable — see Parameters). Positional: yes/y/1/true/t ↔ no/n/0/false/f.list/set/tuple/frozenset: consume multiple tokens; tuples are fixed-length.dict[K, V]: --mapping.key value (dot-notation); dict[str, X] also takes a JSON object (--mapping='{"a": 1}') from the CLI or an env var.Literal[...], Enum (case-insensitive name match, not value), Union / Optional (left-to-right).none / null (case-insensitive) parse to None for optional types: int | None gets None, but str | None and Path | None keep the literal string because the first member already accepts it.tuple[int, int] | int. bool | list[str] works as a bare flag or with values; so does Foo | bool for a class Foo (bare --x / --no-x, or keyed --x.field).date/datetime/timedelta parse ISO.--movie='{"title":"Dune"}').Parameter(converter=fn).cyclopts.types — prebuilt validator shortcutsPrefer these over hand-rolling Parameter(validator=validators.Path(...)) etc. Each is a thin Annotated[base, Parameter(validator=...)] alias, so they compose with further Annotated[...] if needed.
from cyclopts.types import ExistingFile, PositiveInt, Port
def serve(config: ExistingFile, port: Port = 8080, workers: PositiveInt = 1): ...
Names compose from a predictable scheme, so guess the name, then confirm with the lookup below:
{prefix}{kind}, where prefix is empty (type/extension only, no existence check), Existing, NonExistent (outputs that shouldn't clobber), or Resolved (calls .resolve(); combines as ResolvedExisting…), and kind is Path, File, Directory, or an extension type (CsvPath, JsonPath, TomlPath, YamlPath, ImagePath, …).{Positive,Negative,NonNegative,NonPositive}{Int,Float}, sized Int8…UInt64 / HexUInt…, and ranges NormFloat (0–1), SignedNormFloat (-1–1), PercentInt (0–100), Port.Email, URL, Json (parsed JSON), StdioPath (- means stdin/stdout).The full list for the installed version: python -c 'import cyclopts.types as t; print(t.__all__)'.
cyclopts.types doesn't have it)from cyclopts import validators
# Param-level — built-ins:
Parameter(validator=validators.Path(exists=True, ext=(".npz",)))
Parameter(validator=validators.Number(gte=0, lt=16))
# Your own — raise AssertionError / TypeError / ValidationError; cyclopts formats it for the user.
def must_be_even(type_, value) -> None:
if value % 2: raise AssertionError("value must be even")
Parameter(validator=[validators.Number(gte=0), must_be_even]) # list = AND
@dataclass
class Common:
url: str = "http://example.com"
verbose: bool = False
# Flatten so flags are --url not --common.url:
@app.command
def run(cfg: Annotated[Common | None, Parameter(name="*")] = None):
cfg = cfg or Common()
Use the Parameter(name="*") trick to share a config dataclass across multiple commands without writing a meta app. When every field has a default, the parameter itself needs one too (the | None = None above); cyclopts raises ValueError at registration otherwise.
A Group groups commands or parameters under one help panel, and can validate them jointly.
from cyclopts import Group, Parameter, validators
# Cross-parameter validation: exactly one of {--car, --bike, --plane} must be set.
g_vehicle = Group("Vehicle (choose one)", validator=validators.MutuallyExclusive())
@app.command(group="Admin") # implicit string-keyed help panel
def info(): ...
@app.command
def travel(
car: Annotated[bool, Parameter(group=g_vehicle)] = False,
bike: Annotated[bool, Parameter(group=g_vehicle)] = False,
plane: Annotated[bool, Parameter(group=g_vehicle)] = False,
): ...
# Multiple groups on one param: Parameter(group=(g_vehicle, g_payments))
# Preserve declaration order in the help panel (instead of alphabetical):
g_plants = Group.create_ordered("Plants")
Available group validators: validators.MutuallyExclusive() (alias for LimitedChoice() defaults), validators.LimitedChoice(min=1, max=2), validators.all_or_none.
*args / **kwargs@app.command
def add(name: str, *favorites: int, **tags: str):
"""`myapp add Brian 1 2 3 --color blue --size large` →
name='Brian', favorites=(1,2,3), tags={'color':'blue','size':'large'}"""
Named function params fill first, then leftover --key value go to **kwargs, then remaining positionals go to *args. Each is cast to its annotated type.
app = App(
name="myapp",
help="What myapp does.", # overrides the App's own docstring
help_flags=("--help", "-h"), # "" disables
help_format="markdown", # "markdown" (default) | "rst" | "rich" | "plaintext"
version="1.2.3", # str, callable, or omit → auto-discovers via importlib.metadata / __version__
version_flags=("--version", "-V"),
)
App-help resolution (highest wins): decorator help= → registered App.help attribute → function __doc__ → meta app docstring. (Per-parameter help comes from the docstring; see Mental model.)
from cyclopts import App, config
app = App(config=[
config.Env("MYAPP_"), # higher prio
config.Toml("pyproject.toml", root_keys=["tool", "myapp"], search_parents=True),
config.Yaml("config.yaml"),
config.Json("config.json"),
])
Priority: CLI > env > file > Python defaults.
config.Env("MYAPP_") reads MYAPP_<COMMAND>_<PARAM>, upper-cased, with hyphens in command names turned into underscores (ship-it --n → MYAPP_SHIP_IT_N; before 5.5 the hyphen stayed). config.Env("MYAPP_", command=False) drops the command part.
@app.meta.default
def launcher(
*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)],
user: str, # global flag visible on every subcommand
):
setup(user)
app(tokens) # forward to the real app
Meta inherits parent config, merges into help. @app.meta.command bypasses the launcher (good for --help-style ops). For programmatic launch via app.meta(...).
Where global flags may appear is set by App(parse_mode=...), inherited by sub-apps:
"fallthrough" (default): meta flags work anywhere (myapp --user x cmd and myapp cmd --user x). When the subcommand defines the same flag, the subcommand wins for tokens after it. A subcommand whose only positional is a catch-all *args with allow_leading_hyphen=True claims everything after it, so put meta flags before it."strict": flags bind only at the level where they appear (Click/Typer scoping); a meta flag after the subcommand is rejected with a hint, and child help omits parent flags.Forwarded *tokens keep a user-typed --, so the inner parse still treats what follows as positional.
app.command("myapp.commands.users:create") # imports only on invocation
app.command("myapp.admin:admin_app", name="admin")
user_app.command("myapp.commands.users:list_users", name="list")
Parent help renders without importing. Import errors surface at invocation; you can pre-touch app["create"] in tests to catch them early. Define Group objects in non-lazy modules so they exist before the lazy module loads.
app() # uses sys.argv[1:] and sys.exit()s
app("foo 1 2 3") # str -> shlex.split
app(["foo", "1", "2", "3"]) # list
# Embedding / tests: don't exit, hand back return value:
app(["foo"], result_action="return_value")
# Or globally:
App(result_action="return_value")
Error knobs on App (override per-call): exit_on_error=True, print_error=True, help_on_error=False, verbose=False. Cyclopts maintains separate console (stdout) and error_console (stderr).
from cyclopts.types import StdioPath
@app.default
def process(input_: StdioPath, output: StdioPath = StdioPath("-")):
output.write_text(input_.read_text().upper())
- means stdin (read) / stdout (write). For < 3.12: take Optional[Path], branch on None.
# pyproject.toml
[project.scripts]
myapp = "mypackage.__main__:app"
app must be the App instance, not a wrapper function.
Ordered roughly by how silently they bite: top entries fail without obvious errors.
| Symptom | Fix |
|---|---|
| Dataclass / pydantic fields silently ignored or misparsed | Use plain annotations in modules defining commands or command dataclasses: remove from __future__ import annotations (PEP-563 string hints are only partially supported; cross-module dataclass inheritance breaks) |
| Enum input rejected when typing the value | Cyclopts matches enum name (case-insensitive), not value. Use Literal[...] for value matching |
--help shows nothing for a parameter | Key the docstring Parameters entry by the Python variable name, not the CLI flag |
myapp --name=Alice 3 or myapp 3 --name=Alice fails | Python binding rules apply: once a parameter is passed by keyword, pass the later ones by keyword too (myapp Alice 3 and myapp --name Alice --count 3 both work) |
TypeError: Cannot register a sub-App to default | @app.default takes functions only; give the sub-app its own @sub.default function |
ValueError at registration: "has all optional values, uses Parameter(name="*")" | Give the flattened dataclass parameter a default: cfg: Annotated[Common | None, Parameter(name="*")] = None |
myapp mycommand not found for def MyCommand / def my_command | Command names match exactly: my-command |
--version / --help on a subcommand binds a parameter instead of printing | The command defines a parameter with that name, which shadows the built-in flag; rename it |
| Error flattening a sub-app | Pass name="*" alone in app.command(other_app, name="*"); flattening accepts no other config |
SystemExit, or a warning about sys.argv, under pytest | Call app([...], result_action="return_value") with an explicit token list |
RepeatArgumentError: --foo specified multiple times | Scalar type got --foo a --foo b. Switch to list[X], or Parameter(allow_repeating=True) for last-wins |
RequiresEqualsError | Param has requires_equals=True; use --option=value |
Unexpected --no-X / --empty-X in help | Auto-pair for bool/iterable; rename with Parameter(negative="...") or disable with Parameter(negative="") |
For topics beyond this file (v4 to v5 migration, parse mode, testing cookbook, shell completion, docs generation, help customization, Sphinx/MkDocs, Typer migration, coercion rules, known issues), read LINKS.md for the page to fetch.
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub tsvikas/skills --plugin cyclopts