API Reference

Parameter class hierarchy

Inheritance diagram of fargv.parameters.FargvInt, fargv.parameters.FargvFloat, fargv.parameters.FargvBool, fargv.parameters.FargvStr, fargv.parameters.FargvChoice, fargv.parameters.FargvPositional, fargv.parameters.FargvTuple, fargv.parameters.FargvStream, fargv.parameters.FargvInputStream, fargv.parameters.FargvOutputStream, fargv.parameters.FargvPath, fargv.parameters.FargvExistingFile, fargv.parameters.FargvNonExistingFile, fargv.parameters.FargvFile, fargv.parameters.FargvSubcommand

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 / -s prefixes. “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_type is 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 RuntimeError when called at module level or when the calling function cannot be resolved.

Returns:

(namespace, help_str) – same as parse().

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: FargvParameter

Integer parameter.

When is_count_switch=True the parameter acts as a verbosity counter:

  • Bare repeated short flags -vvv increment the counter by one per flag.

  • An explicit value --verbosity=3 sets 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_switch is False.

class fargv.FargvFloat(default: float = 0.0, name: str | None = None, short_name: str | None = None, description: str | None = None)[source]

Bases: FargvParameter

Floating-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: FargvParameter

Boolean 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 (or 1/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" are True; anything else is False.

Parameters:

valbool, int, or str.

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/false when 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: FargvParameter

String parameter supporting {key} cross-parameter interpolation.

When other_string_params is populated (by dict_to_parser()), any {key} placeholder in the value is resolved at read time using the current value of the named FargvStr sibling.

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_params dict is wired up automatically when building a parser from a plain dict via dict_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 FargvParameter instances.

Used during value resolution 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. FargvStr siblings 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: FargvParameter

Enumerated-choice parameter (analogous to a tuple default 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.

ingest_value_strings(*values: List[str]) List[str][source]

Parse the first token and validate it against the allowed choices.

Parameters:

values – Raw argv tokens.

Returns:

Unconsumed tokens.

Raises:

FargvError – When no token is given, or the token is not a valid choice.

validate_value_strings(*values: List[str]) bool[source]

Return True when exactly one value is provided and it is in choices.

Parameters:

values – Raw argv tokens to validate.

Returns:

True if valid.

Raises:

FargvError – When the wrong number of tokens is supplied.

fargv.FargvPositional[source]

alias of FargvVariadic

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: FargvParameter

Fixed-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,)" when element_types=(int,).

Optional tuples: with optional=True, the empty-tuple string "()" (or an actual empty tuple) produces None instead 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] and Optional[Tuple[int, int]] in function signatures are automatically mapped to this class by function_to_parser().

docstring(colored=None, verbosity=None) str[source]

Return a one-line help string including element types and optional flag.

evaluate(val: Any) Any[source]

Set the value from a tuple, None, or a string representation.

Parameters:

valtuple, None (only when optional=True), or string.

Returns:

The stored value.

Raises:

FargvError – On length/type mismatches.

ingest_value_strings(*values: List[str]) List[str][source]

Parse the first token as a typed tuple.

Parameters:

values – Raw argv tokens.

Returns:

Unconsumed tokens.

Raises:

FargvError – When no token is supplied or parsing fails.

class fargv.FargvStream(default: TextIOBase | Literal['stderr', 'stdout', 'stdin'], name: str | None = None, short_name: str | None = None, description: str | None = None)[source]

Bases: FargvParameter

Text I/O stream parameter.

The value is a file-like object (io.TextIOBase or 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 .mode attribute

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 FargvInputStream and FargvOutputStream over this base class.

ingest_value_strings(*values: List[str]) List[str][source]

Open the stream described by the first token.

Special keywords stdin, stdout, and stderr map to the corresponding sys objects. 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 True if 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:

True when 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: FargvStream

Text 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: FargvStream

Text 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 stdout and stderr are 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: FargvParameter

File-system path parameter returning a pathlib.Path.

Three optional validation constraints are available (all False by 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, and FargvFile for the most common constraint patterns.

docstring(colored=None, verbosity=None) str[source]

Return a one-line help string including any active path constraints.

evaluate(val) Path[source]

Set the value from a string or pathlib.Path, then validate.

Parameters:

val – String or pathlib.Path.

Returns:

The stored pathlib.Path.

Raises:

FargvError – When validation fails.

ingest_value_strings(*values: List[str]) List[str][source]

Parse the first token as a path and validate it.

Parameters:

values – Raw argv tokens.

Returns:

Unconsumed tokens.

Raises:

FargvError – When no token is given or validation fails.

class fargv.FargvExistingFile(default=None, name=None, short_name=None, description=None)[source]

Bases: FargvPath

Path 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: FargvPath

Path 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: FargvPath

Path 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: FargvParameter

A 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 commit or docker run).

The definition dict maps subcommand names to their own definitions — plain dicts, callables, or ArgumentParser instances; any value accepted by definition_to_parser().

CLI forms (both are recognised):

  • Git-style positional: myscript train --lr=0.1

  • Flag 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. When mandatory=True, omitting a subcommand raises FargvError.

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

True when 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 prog name).

  • long_prefix – Long flag prefix, typically "--".

  • key – This parameter’s name (used to build --key= prefix).

Returns:

(subcommand_name, remaining_tokens) where subcommand_name is None when 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

fargv.REQUIRED = REQUIRED

Singleton sentinel used as a default value to mark mandatory parameters.

Use the module-level REQUIRED constant rather than constructing this class directly.


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: object

Low-level Unix-style argument parser for fargv.

Builds a mapping from parameter names to FargvParameter instances, then parses a sys.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 FargvSubcommand parameter 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] when None.

  • parameters – Optional list or dict of FargvParameter instances to pre-register.

  • allow_default_variadic – When True (default), a single FargvVariadic param 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:
  • coloredTrue/False/None (auto-detect TTY).

  • verbosity – When None the global verbosity from get_verbosity() is used. Descriptions and env-var hints are shown only when verbosity > 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_name is currently None are 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_epochs with n, N, e, E all taken would try u, 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.argv when None.

  • 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 ArgumentParser from a plain-Python dict definition.

Each key becomes a parameter name. Each value is passed to _infer_param() to produce the appropriate FargvParameter subclass.

After construction, all FargvStr parameters are linked to each other via their other_string_params dict to enable {key} cross-interpolation.

Parameters:
  • definition – Mapping of parameter names to default values (or pre-built FargvParameter instances).

  • 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 from field.default or field.default_factory(). Fields with no default are marked mandatory. Fields whose type is unrecognisable and whose default is None are skipped (same rule as function_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 no description= is already set on the Fargv* 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 what deep_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.