API Reference
Parameter class hierarchy

Main entry points
- fargv.parse(definition: type[_DC], given_parameters: Dict[str, Any] | List[str] | None = None, **kwargs: Any) Tuple[_DC, str][source]
- fargv.parse(definition: Dict[str, Any] | ArgumentParser | Callable, given_parameters: Dict[str, Any] | List[str] | None = None, **kwargs: Any) Tuple[Any, str]
Parse CLI arguments using the fargv interface.
- Priority order when config is enabled:
coded defaults → config file → CLI / UI
- Parameters:
definition – dict (type-inferred), ArgumentParser (pass-through), or callable (signature introspection). A nested dict whose values are all definitions is inferred as a subcommand parameter.
given_parameters – None → sys.argv; List[str] → argv; Dict[str,Any] → direct evaluate.
argv_parse_mode – “unix” (default) —
--long/-sprefixes. “legacy” — single-dash-name=value. Ignored when definition is an ArgumentParser.allow_implied_variadics – Route leftover tokens to the single defined variadic.
tolerate_unassigned_arguments – Silently discard leftovers with no variadic to receive them.
auto_define_config – Inject
--config <path>parameter. Default config path:~/.{app_name}.config.json.override_order – Controls which source takes precedence. Each subsequent source overrides earlier ones. Must start with
"default"and end with"ui"; duplicates are rejected. Default:["default", "config", "envvar", "ui"].employ_docstring_in_help – When
True(default), the docstring of definition (or the calling module when definition is a dict) is prepended to the help string under a__doc__:heading. Printed in gray when colours are active.subcommand_return_type – “flat” (default) — subcommand params merged into top-level namespace, subcommand key holds the selected name. “nested” — subcommand key holds a SimpleNamespace(name=…,
**params). “tuple” — returns ((name, sub_ns, parent_ns), help_str).
- fargv.parse_and_launch(fn: Callable, given_parameters: Dict[str, Any] | List[str] | None = None, argv_parse_mode: Literal['legacy', 'unix'] = 'unix', allow_implied_variadics: bool = True, tolerate_unassigned_arguments: bool = False, ui: Literal['cli', 'tk', 'qt', 'jupyter'] | None = None, auto_define_help: bool = True, auto_define_bash_autocomplete: bool = True, auto_define_verbosity: bool = True, auto_define_config: bool = True, auto_define_user_interface: bool = True, colored_help: bool | None = None, subcommand_return_type: Literal['flat', 'nested', 'tuple'] = 'flat', non_defaults_are_mandatory: bool = False, fn_def_tolerate_wildcards: bool = False, override_order: List[Literal['default', 'config', 'envvar', 'ui']] = ['default', 'config', 'envvar', 'ui'], employ_docstring_in_help: bool = True) Any[source]
Parse CLI arguments inferred from fn’s signature, then call fn.
Equivalent to
p, _ = parse(fn, ...); return fn(**p).return_typeis always"dict"internally so auto-params are filtered before the call.- Parameters:
fn – Callable whose signature defines the parameters.
- Returns:
The return value of fn.
- fargv.parse_here(given_parameters: Dict[str, Any] | List[str] | None = None, argv_parse_mode: Literal['legacy', 'unix'] = 'unix', allow_implied_variadics: bool = True, tolerate_unassigned_arguments: bool = False, ui: Literal['cli', 'tk', 'qt', 'jupyter'] | None = None, auto_define_help: bool = True, auto_define_bash_autocomplete: bool = True, auto_define_verbosity: bool = True, auto_define_config: bool = True, auto_define_user_interface: bool = True, colored_help: bool | None = None, subcommand_return_type: Literal['flat', 'nested', 'tuple'] = 'flat', non_defaults_are_mandatory: bool = False, fn_def_tolerate_wildcards: bool = False, override_order: List[Literal['default', 'config', 'envvar', 'ui']] = ['default', 'config', 'envvar', 'ui'], employ_docstring_in_help: bool = True, return_type: Literal['SimpleNamespace', 'dict', 'namedtuple', 'namespace'] = 'SimpleNamespace') Tuple[Any, str][source]
Parse CLI arguments inferred from the calling function’s signature.
Must be called from inside a named function. Raises
RuntimeErrorwhen called at module level or when the calling function cannot be resolved.- Returns:
(namespace, help_str)– same asparse().- Raises:
RuntimeError – When called outside a function.
Parameter classes
All parameter classes are exported directly from the fargv package.
- class fargv.FargvInt(default: int = 0, name: str | None = None, short_name: str | None = None, description: str | None = None, is_count_switch: bool = False)[source]
Bases:
FargvParameterInteger parameter.
When
is_count_switch=Truethe parameter acts as a verbosity counter:Bare repeated short flags
-vvvincrement the counter by one per flag.An explicit value
--verbosity=3sets it directly.A non-integer token after the flag is treated as a positional leftover and the counter is incremented by one.
Example:
FargvInt(0, name="verbosity", short_name="v", is_count_switch=True) # -vvvv → 4 # --verbosity=2 → 2
- docstring(colored=None, verbosity=None) str[source]
Return a one-line help string, appending a count-switch note when relevant.
- ingest_value_strings(*values: List[str]) List[str][source]
Parse one integer token, or increment the counter when acting as a count switch.
- Parameters:
values – Raw argv tokens following the flag.
- Returns:
Unconsumed tokens.
- Raises:
FargvError – When no value is provided and
is_count_switchisFalse.
- class fargv.FargvFloat(default: float = 0.0, name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterFloating-point parameter.
Accepts any string that Python’s
float()constructor accepts, including"1e-3","inf", and"nan".Example:
FargvFloat(0.001, name="lr") # --lr=1e-4 → 0.0001
- class fargv.FargvBool(default: bool = False, name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterBoolean flag parameter.
A bare
--flag(no value) toggles the default:FargvBool(False, name="verbose") # --verbose → True FargvBool(True, name="debug") # --debug → False
An explicit value
--flag=true/--flag=false(or1/0,t/f) overrides the toggle behaviour.- docstring(colored=None, verbosity=None) str[source]
Return a one-line help string, appending a switch note when default is
False.
- evaluate(val) bool[source]
Set the value from a bool, int, or truthy string.
Accepted string values (case-insensitive):
"true"/"1"/"t"areTrue; anything else isFalse.- Parameters:
val –
bool,int, orstr.- Returns:
The stored bool.
- Raises:
FargvError – When val is none of the accepted types.
- ingest_value_strings(*values: List[str]) List[str][source]
Toggle on bare call; accept
0/1/t/f/true/falsewhen a value is supplied.- Parameters:
values – Zero or one raw argv token.
- Returns:
Unconsumed tokens.
- Raises:
FargvError – When the supplied value is not a recognised boolean string.
- property is_bool: bool
Always
True— marks this as a toggleable boolean flag.
- class fargv.FargvStr(default: str = '', name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterString parameter supporting
{key}cross-parameter interpolation.When
other_string_paramsis populated (bydict_to_parser()), any{key}placeholder in the value is resolved at read time using the current value of the namedFargvStrsibling.Example:
base = FargvStr("/tmp", name="base") out = FargvStr("{base}/results", name="out") out.other_string_params = {"base": base} print(out.value) # "/tmp/results"
Circular references that would cause infinite recursion are detected and left as literal
{key}placeholders rather than raising an exception.Note
The
other_string_paramsdict is wired up automatically when building a parser from a plain dict viadict_to_parser(). It does not need to be set manually in most cases.- property is_string: bool
Always
True— marks this parameter as supporting interpolation.
- other_string_params: Dict[str, FargvParameter]
Mapping from parameter names (any type) to their
FargvParameterinstances.Used during
valueresolution to expand{key}placeholders. Any parameter type is accepted:{epochs}resolves an int param, etc. Populated automatically by_link_string_params().
- property value: str
Return the current string value with
{key}references resolved.Any registered parameter can be referenced by name.
FargvStrsiblings are resolved recursively; other types are stringified. Unknown keys and cycles are left as literal{key}placeholders.- Returns:
Fully interpolated string.
- class fargv.FargvChoice(choices: List[str], default: str | None = None, name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterEnumerated-choice parameter (analogous to a
tupledefault in the legacy API).The accepted values are defined at construction time. Passing a value not in the list raises
FargvError.Example:
FargvChoice(["adam", "sgd", "rmsprop"], name="optimizer") # --optimizer=sgd → "sgd" # --optimizer=lion → FargvError
The first element is the default unless default is supplied explicitly:
FargvChoice(["a", "b", "c"], default="b", name="mode")
- docstring(colored=None, verbosity=None) str[source]
Return a one-line help string that includes the allowed choices.
- evaluate(val) str[source]
Set the value from a string or object coercible to string.
- Parameters:
val – Candidate value.
- Returns:
The stored string.
- Raises:
FargvError – When the coerced string is not in
_choices.
- class fargv.FargvTuple(element_types: tuple, default=None, optional: bool = False, name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterFixed-length typed tuple parsed from a single
(a, b, c)string.Uses
ast.literal_eval()so standard Python tuple syntax is accepted. Element types must be basic Python built-ins (int,float,str,bool,bytes).Single-element shorthand:
"42"is equivalent to"(42,)"whenelement_types=(int,).Optional tuples: with
optional=True, the empty-tuple string"()"(or an actual empty tuple) producesNoneinstead of raising an error.Example:
FargvTuple((int, int), name="size") # --size=(640,480) → (640, 480) FargvTuple((int, int), optional=True, name="crop") # --crop=() → None # --crop=(224,224) → (224, 224)
The annotation
Tuple[int, int]andOptional[Tuple[int, int]]in function signatures are automatically mapped to this class byfunction_to_parser().- docstring(colored=None, verbosity=None) str[source]
Return a one-line help string including element types and optional flag.
- class fargv.FargvStream(default: TextIOBase | Literal['stderr', 'stdout', 'stdin'], name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterText I/O stream parameter.
The value is a file-like object (
io.TextIOBaseor its subclasses). On the command line the user supplies either a special keyword (stdin,stdout,stderr) or a file path.The stream mode (
"r","w", or"a") is inferred from the default value passed at construction time:sys.stdin→"r"sys.stdout→"w"sys.stderr→"w"An open file handle → its
.modeattribute
Write-mode streams refuse to open paths that already exist (to prevent accidental overwriting). Parent directories are created automatically when a path is given in write or append mode.
Note
Prefer the concrete subclasses
FargvInputStreamandFargvOutputStreamover this base class.- ingest_value_strings(*values: List[str]) List[str][source]
Open the stream described by the first token.
Special keywords
stdin,stdout, andstderrmap to the correspondingsysobjects. Any other string is treated as a file path and opened in the stream’s mode.- Parameters:
values – One or more raw argv tokens.
- Returns:
Unconsumed tokens.
- Raises:
FargvError – When no token is supplied.
AssertionError – On mode mismatches (e.g. writing to stdin) or when a write-mode path already exists.
ValueError – When the stream mode is not
"r","w", or"a".
- validate_value_strings(value: str) bool[source]
Return
Trueif value names a usable stream target.Read mode (
"r"): the path must be openable for reading.Write mode (
"w"): the path must not already exist and its parent hierarchy must be writable.Other modes: always
False.
- Parameters:
value – Path string or stream keyword.
- Returns:
Truewhen the value is acceptable.
- property value_str: str
Return a human-readable description of the current stream.
- class fargv.FargvInputStream(default=None, name=None, short_name=None, description=None)[source]
Bases:
FargvStreamText input stream; defaults to
sys.stdin.On the command line a file path may be supplied to redirect input:
FargvInputStream(name="data") # --data=corpus.txt → open("corpus.txt", "r") # (no flag) → sys.stdin
- class fargv.FargvOutputStream(default=None, name=None, short_name=None, description=None)[source]
Bases:
FargvStreamText output stream; defaults to
sys.stdout.On the command line a file path may be supplied to redirect output:
FargvOutputStream(name="out") # --out=results.txt → open("results.txt", "w") # (no flag) → sys.stdout
The keywords
stdoutandstderrare also accepted.
- class fargv.FargvPath(default=None, must_exist: bool = False, must_not_exist: bool = False, parent_must_exist: bool = False, name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterFile-system path parameter returning a
pathlib.Path.Three optional validation constraints are available (all
Falseby default):must_exist— the path must already exist on disk.must_not_exist— the path must NOT exist (safe output target).parent_must_exist— the parent directory must already exist.
Example:
FargvPath(must_exist=True, name="model") # --model=/weights/best.pt → validates and returns Path("/weights/best.pt")
Prefer the convenience subclasses
FargvExistingFile,FargvNonExistingFile, andFargvFilefor the most common constraint patterns.- docstring(colored=None, verbosity=None) str[source]
Return a one-line help string including any active path constraints.
- class fargv.FargvExistingFile(default=None, name=None, short_name=None, description=None)[source]
Bases:
FargvPathPath that must point to an existing file system entry.
Equivalent to
FargvPath(must_exist=True).
- class fargv.FargvNonExistingFile(default=None, name=None, short_name=None, description=None)[source]
Bases:
FargvPathPath that must NOT already exist on disk (prevents accidental overwrite).
Equivalent to
FargvPath(must_not_exist=True).
- class fargv.FargvFile(default=None, name=None, short_name=None, description=None)[source]
Bases:
FargvPathPath whose parent directory must already exist.
Use this for output files where the directory is expected to exist but the file itself may or may not. Equivalent to
FargvPath(parent_must_exist=True).
- class fargv.FargvSubcommand(definitions: Dict[str, Any], mandatory: bool = False, name: str | None = None, short_name: str | None = None, description: str | None = None)[source]
Bases:
FargvParameterA subcommand parameter whose value is a nested argument namespace.
Maps a set of sub-parser definitions to a single positional-style token on the command line (like
git commitordocker run).The definition dict maps subcommand names to their own definitions — plain dicts, callables, or
ArgumentParserinstances; any value accepted bydefinition_to_parser().CLI forms (both are recognised):
Git-style positional:
myscript train --lr=0.1Flag style:
myscript --cmd=train --lr=0.1
Everything before the subcommand token is treated as parent-level args; everything after is passed to the subcommand’s own parser.
Defaults: when
mandatory=False(the default), the first key in definitions is used as the default subcommand. Whenmandatory=True, omitting a subcommand raisesFargvError.Example:
p = ArgumentParser() p._add_parameter(FargvSubcommand( {"train": {"lr": 0.01}, "eval": {"dataset": "val"}}, name="cmd", )) result = p.parse(["prog", "train", "--lr=0.5"]) # result["cmd"] == {"name": "train", "result": {"lr": 0.5}}
- docstring(colored=None, verbosity=None) str[source]
Return a help string showing available subcommand names and their parameters.
- property has_value: bool
Truewhen a subcommand has been selected (either by parsing or default).
- ingest_value_strings(*values)[source]
Not supported — subcommand parsing is handled by
ArgumentParser.- Raises:
FargvError – Always.
- property is_subcommand: bool
Always
True— identifies this as a subcommand parameter.
- parse_subcommand(sub_name: str, sub_tokens, long_prefix: str, short_prefix: str) dict[source]
Parse sub_tokens using the pre-built parser for sub_name.
- Parameters:
sub_name – Name of the subcommand to parse.
sub_tokens – Argv tokens for the subcommand.
long_prefix – Long flag prefix (e.g.
"--").short_prefix – Short flag prefix (e.g.
"-").
- Returns:
Parsed namespace dict from the subcommand’s parser.
- split_argv(argv, long_prefix: str, key: str)[source]
Find the subcommand token; return (sub_name_or_None, all_remaining_tokens).
The subcommand token is removed from the returned list so that the caller can freely route the remaining tokens between parent and sub parsers.
- Parameters:
argv – Full argv list (not including
progname).long_prefix – Long flag prefix, typically
"--".key – This parameter’s name (used to build
--key=prefix).
- Returns:
(subcommand_name, remaining_tokens)where subcommand_name isNonewhen no subcommand was found.- Raises:
FargvError – When a flag-style subcommand names an unknown subcommand.
- property value: Dict[str, Any]
Return a dict
{"name": <selected_name>, "result": <sub_namespace_dict>}.name— the selected subcommand name.result— the parsed namespace dict returned by the sub-parser.
Sentinel
Low-level parser
- class fargv.parser.ArgumentParser(progname: str | None = None, parameters: List[FargvParameter] | Dict[str, FargvParameter] | None = None, allow_default_variadic: bool = True, auto_help: bool = True, auto_bash_autocomplete: bool = True, long_prefix: str = '--', short_prefix: str = '-')[source]
Bases:
objectLow-level Unix-style argument parser for fargv.
Builds a mapping from parameter names to
FargvParameterinstances, then parses asys.argv-style token list into a{name: value}dict.Typical usage via the high-level API:
from fargv import parse params, help_str = parse({"lr": 0.01, "epochs": 10})
Direct usage (for full control):
from fargv.parser import ArgumentParser from fargv.parameters import FargvInt, FargvBool p = ArgumentParser(progname="mytool") p._add_parameter(FargvInt(10, name="epochs")) p._add_parameter(FargvBool(False, name="verbose", short_name="v")) result = p.parse() # reads sys.argv
Subcommands are handled transparently when a
FargvSubcommandparameter is present. The parser splits argv at the subcommand token, parses both halves, and merges the results.- Parameters:
progname – Display name used in help and autocomplete output. Auto-detected from
sys.argv[0]whenNone.parameters – Optional list or dict of
FargvParameterinstances to pre-register.allow_default_variadic – When
True(default), a singleFargvVariadicparam automatically absorbs any leftover tokens.auto_help – Deprecated; ignored.
auto_bash_autocomplete – Deprecated; ignored.
long_prefix – Prefix for long flags (default
"--").short_prefix – Prefix for short flags (default
"-").
- generate_bash_autocomplete() str[source]
Return a bash completion script for this parser.
Source it in a shell session to enable tab-completion:
source <(myprog --bash_autocomplete)
When subcommand parameters are present the script context-switches to the subcommand’s own flag set once a subcommand name has been typed.
- Returns:
Multi-line bash script string.
- generate_help_message(colored=None, verbosity=None) str[source]
Return a multi-line help message listing all registered parameters.
- Parameters:
colored –
True/False/None(auto-detect TTY).verbosity – When
Nonethe global verbosity fromget_verbosity()is used. Descriptions and env-var hints are shown only whenverbosity > 0.
- Returns:
Formatted help string.
- infer_short_names(parent_taken: set = None) None[source]
Assign short single-character aliases to parameters that lack one.
Only parameters whose
short_nameis currentlyNoneare considered. The algorithm iterates over letter positions[0, 1, 2, ...]and over the_-split words of the parameter name. For each(position, word)pair it tries the character at that position first lower-case then upper-case. The first candidate not already taken is assigned.Example:
num_epochswithn,N,e,Eall taken would tryu,U,p,P, … until one is free.If no single-character candidate is ever free the parameter receives no short name. Already-registered explicit short names (from
_add_parameter()) are never displaced.- Parameters:
parent_taken – Optional set of short names already used by the parent parser, so sub-parsers do not reuse the same characters.
- parse(argv: List[str] | None = None, first_is_name: bool = True, tolerate_unassigned_arguments: bool = False) Dict[str, Any][source]
Parse argv and return a
{name: value}result dict.- Parameters:
argv – Token list to parse. Defaults to
sys.argvwhenNone.first_is_name – When
True(default), the first element of argv is treated as the program name and stripped.tolerate_unassigned_arguments – When
True, leftover tokens that cannot be assigned to any parameter are silently discarded instead of raising.
- Returns:
{name: value}mapping for every registered parameter.- Raises:
FargvError – On unknown flags, type errors, or missing mandatory params.
Type detection utilities
- fargv.type_detection.definition_to_parser(definition, non_defaults_are_mandatory: bool = False, fn_def_tolerate_wildcards: bool = False, long_prefix: str = '--', short_prefix: str = '-') ArgumentParser[source]
Dispatch definition (dict, ArgumentParser, or callable) to the right converter.
- fargv.type_detection.dict_to_parser(definition: Dict[str, Any], long_prefix: str = '--', short_prefix: str = '-') ArgumentParser[source]
Build an
ArgumentParserfrom a plain-Python dict definition.Each key becomes a parameter name. Each value is passed to
_infer_param()to produce the appropriateFargvParametersubclass.After construction, all
FargvStrparameters are linked to each other via theirother_string_paramsdict to enable{key}cross-interpolation.- Parameters:
definition – Mapping of parameter names to default values (or pre-built
FargvParameterinstances).long_prefix – Long flag prefix (default
"--").short_prefix – Short flag prefix (default
"-").
- Returns:
Configured
ArgumentParser.- Raises:
FargvError – When a value’s type cannot be inferred.
- fargv.type_detection.function_to_parser(fn: Callable, non_defaults_are_mandatory: bool = False, fn_def_tolerate_wildcards: bool = False, long_prefix: str = '--', short_prefix: str = '-') ArgumentParser[source]
Derive an ArgumentParser from a function’s type-annotated signature.
- fargv.type_detection.dataclass_to_parser(cls, long_prefix: str = '--', short_prefix: str = '-') ArgumentParser[source]
Derive an ArgumentParser from a dataclass class.
Field types are read from
typing.get_type_hints(); defaults come fromfield.defaultorfield.default_factory(). Fields with no default are marked mandatory. Fields whose type is unrecognisable and whose default isNoneare skipped (same rule asfunction_to_parser()).Attribute docstrings (bare string literals immediately following a field definition) are extracted via
_extract_field_docstrings()and used as the parameter description when nodescription=is already set on theFargv*instance.Two-level subcommand rule: when a field’s type annotation is a dataclass that itself has all fields annotated as dataclasses, that field is treated as a
FargvSubcommand. Field names of the inner dataclass become branch names; field types become branch definitions. This is whatdeep_dataclass()produces from nested inner-class syntax.- Parameters:
cls – A dataclass class (not an instance).
long_prefix – Long flag prefix (default
"--").short_prefix – Short flag prefix (default
"-").
- Returns:
Configured
ArgumentParser.- Raises:
TypeError – When cls is not a dataclass class.