API reference¶
Effortless argument parser.
Run Python functions from the command line with run(func)
.
- defopt.run(funcs, *, parsers={}, short=None, cli_options='kwonly', show_defaults=True, show_types=False, no_negated_flags=False, version=None, argparse_kwargs={}, intermixed=False, argv=None)¶
Process command-line arguments and run the given functions.
funcs can be a single callable, which is parsed and run; or it can be a list of callables or mappable of strs to callables, in which case each one is given a subparser with its name (if funcs is a list) or the corresponding key (if funcs is a mappable), and only the chosen callable is run. Nested mappables are also supported; they define nested subcommands.
See Features for the detailed mapping from function signature to command-line parsing. Note that all docstrings must be valid RST conforming to Sphinx-, Google-, or Numpy-style.
- Parameters:
funcs (Callable | List[Callable] | Dict[str, Callable | List[Callable] | Dict[str, Funcs]]) – Function or functions to process and run.
parsers (Dict[type, Callable[[str], Any]]) – Dictionary mapping types to parsers to use for parsing function arguments.
short (Dict[str, str] | None) – Dictionary mapping parameter names (after conversion of underscores to dashes) to letters, to use as alternative short flags. Defaults to
None
, which means to generate short flags for any non-ambiguous option. Set to{}
to completely disable short flags.cli_options (Literal['kwonly', 'all', 'has_default']) – The default behavior (‘kwonly’) is to convert keyword-only parameters to command line flags, and non-keyword-only parameters with a default to optional positional command line parameters. ‘all’ turns all parameters into command-line flags. ‘has_default’ turns a parameter into a command-line flag if and only if it has a default value.
show_defaults (bool) – Whether parameter defaults are appended to parameter descriptions.
show_types (bool) – Whether parameter types are appended to parameter descriptions.
no_negated_flags (bool) – If
False
(default), for any non-positional bool options, two flags are created:--foo
and--no-foo
. IfTrue
, the--no-foo
is not created for every such option that has a default valueFalse
.version (str | None | bool) – If a string, add a
--version
flag which prints the given version string and exits. IfTrue
, the version string is auto-detected by searching for a__version__
attribute on the module where the function is defined, and its parent packages, if any. Error out if such a version cannot be found, or if multiple callables with different version strings are passed. IfNone
(the default), behave as forTrue
, but don’t add a--version
flag if no version string can be autodetected. IfFalse
, do not add a--version
flag.argparse_kwargs (dict) – A mapping of keyword arguments that will be passed to the
ArgumentParser
constructor.intermixed (bool) – Whether to use
parse_intermixed_args
to parse the command line. Intermixed parsing imposes many restrictions, listed in theargparse
documentation.argv (List[str] | None) – Command line arguments to parse (default:
sys.argv[1:]
).
- Returns:
The value returned by the function that was run.
- defopt.signature(func)¶
Return an enhanced signature for
func
.This function behaves similarly to
inspect.signature
, with the following differences:The parsed function docstring (which will be used as the parser description) is available as
signature.doc
; likewise, parameter docstrings are available asparameter.doc
. The tuple of raisable exception types is available is available assignature.raises
. (This is done by using subclasses ofinspect.Signature
andinspect.Parameter
.)Private parameters (starting with an underscore) are not listed.
Parameter types are also read from
func
’s docstring (if a parameter’s type is specified both in the signature and the docstring, both types must match).It is also possible to pass a docstring instead of a callable as func; in that case, a Signature is still returned, but all parameters are considered positional-or-keyword, with no default, and the annotations are returned as strs.
This API is provisional and may be adjusted depending on feedback.
- defopt.bind(*args, **kwargs)¶
Process command-line arguments and bind arguments.
This function takes the same parameters as
defopt.run
, but returns a wrapper callablecall
such thatcall()
represents the call thatdefopt.run
would execute. Note thatcall
takes no arguments; they are bound internally.If there are no documented exceptions that
defopt.run
needs to suppress, thencall
is afunctools.partial
object,call.func
is one of the functions passed tobind
, andcall.args
andcall.keywords
are set according to the command-line arguments.If there are documented exceptions that
defopt.run
needs to suppress, thencall
is a wrapper around that partial object.A generic expression to retrieve the underlying selected function is thus
getattr(call, "__wrapped__", call).func
.This API is provisional and may be adjusted depending on feedback.
- defopt.bind_known(*args, **kwargs)¶
Process command-line arguments and bind known arguments.
This function behaves as
bind
, but returns a pair of 1) thepartial
callable, and 2) a list of unknown command-line arguments, as returned byparse_known_args
.This API is provisional and may be adjusted depending on feedback.