API Reference

Running functions

clize.run(*fn, args=None, catch=(), exit=True, out=None, err=None, **kwargs)[source]

Runs a function or CLI object with args, prints the return value if not None, or catches the given exception types as well as clize.UserError and prints their string representation, then exit with the appropriate status code.

Parameters
  • args (sequence) – The arguments to pass the CLI, for instance ('./a_script.py', 'spam', 'ham'). If unspecified, uses sys.argv.

  • catch (sequence of exception classes) – Catch these exceptions and print their string representation rather than letting Python print an uncaught exception traceback.

  • exit (bool) – If true, exit with the appropriate status code once the function is done.

  • out (file) – The file in which to print the return value of the command. If unspecified, uses sys.stdout

  • err (file) – The file in which to print any exception text. If unspecified, uses sys.stderr.

class clize.Clize(fn=None, **kwargs)[source]

Wraps a function into a CLI object that accepts command-line arguments and translates them to match the wrapped function’s parameters.

Parameters
  • alt (sequence) – Alternate actions the CLI will handle.

  • help_names (sequence of strings) – Names to use to trigger the help.

  • helper_class (a type like ClizeHelp) – A callable to produce a helper object to be used when the help is triggered. If unset, uses ClizeHelp.

  • hide_help (bool) – Mark the parameters used to trigger the help as undocumented.

class clize.SubcommandDispatcher(commands=(), description=None, footnotes=None, **kwargs)[source]

Parser

class clize.parser.CliSignature(parameters)[source]

A collection of parameters that can be used to translate CLI arguments to function arguments.

Parameters

parameters (iterable) – The parameters to use.

converter = clize.parser.default_converter

The converter used by default in case none is present in the annotations.

parameters

An ordered dict of all parameters of this cli signature.

positional

List of positional parameters.

alternate

List of parameters that initiate an alternate action.

named

List of named parameters that aren’t in alternate.

aliases = {}

Maps parameter names to NamedParameter instances.

required = set()

A set of all required parameters.

clize.parser.parameter_converter(obj=None, *, name=None)[source]

Decorates a callable to be interpreted as a parameter converter when passed as an annotation.

It will be called with an inspect.Parameter object and a sequence of objects passed as annotations, without the parameter converter itself. It is expected to return a clize.parser.Parameter instance or Parameter.IGNORE.

clize.parser.default_converter(param, annotations)

The default parameter converter. It is described in detail in The default parameter converter.

clize.parser.use_class(*, name=None, pos=<function unimplemented_parameter at 0x7fd0fe553b80>, varargs=<function unimplemented_parameter at 0x7fd0fe553b80>, named=<function unimplemented_parameter at 0x7fd0fe553b80>, varkwargs=<function unimplemented_parameter at 0x7fd0fe553b80>, kwargs={})[source]

Creates a parameter converter similar to the default converter that picks one of 4 factory functions depending on the type of parameter.

Parameters
  • str (name) – A name to set on the parameter converter.

  • pos (callable that returns a Parameter instance) – The parameter factory for positional parameters.

  • varargs (callable that returns a Parameter instance) – The parameter factory for *args-like parameters.

  • named (callable that returns a Parameter instance) – The parameter factory for keyword parameters.

  • varkwargs (callable that returns a Parameter instance) – The parameter factory for **kwargs-like parameters.

  • kwargs (collections.abc.Mapping) – additional arguments to pass to the chosen factory.

clize.parser.use_mixin(cls, *, kwargs={}, name=None)[source]

Like use_class, but creates classes inheriting from cls and one of PositionalParameter, ExtraPosArgsParameter, and OptionParameter

Parameters
  • cls – The class to use as mixin.

  • kwargs (collections.abc.Mapping) – additional arguments to pass to the chosen factory.

  • name – The name to use for the converter. Uses cls’s name if unset.

class clize.parser.CliBoundArguments(sig, in_args, name, func=None, post_name=NOTHING, args=NOTHING, kwargs=NOTHING, meta=NOTHING) -> None[source]

Command line arguments bound to a CliSignature instance.

Parameters
  • sig (CliSignature) – The signature to bind against.

  • args (sequence) – The CLI arguments, minus the script name.

  • name (str) – The script name.

sig

The signature being bound to.

in_args

The CLI arguments, minus the script name.

name

The script name.

args = []

List of arguments to pass to the target function.

kwargs = {}

Mapping of named arguments to pass to the target function.

meta = {}

A dict for parameters to store data for the duration of the argument processing.

func = None

If not None, replaces the target function.

post_name = []

List of words to append to the script name when passed to the target function.

The following attributes only exist while arguments are being processed:

posparam = iter(sig.positional)

The iterator over the positional parameters used to process positional arguments.

namedparam = dict(sig.aliases)

The dict used to look up named parameters from their names.

It is copied here so that the argument parsing process may add or remove parameters without affecting the original signature.

unsatisfied = set(sig.required)

Required parameters that haven’t yet been satisfied.

not_provided = set(sig.optional)

Optional parameters that haven’t yet received a value.

sticky = None

If not None, a parameter that will keep receiving positional arguments.

posarg_only = False

Arguments will always be processed as positional when this is set to True.

skip = 0

Amount of arguments to skip.

Method generated by attrs for class CliBoundArguments.

class clize.parser.Parameter(display_name, undocumented=False, last_option=None)[source]

Bases: object

Represents a CLI parameter.

Parameters
  • display_name (str) – The ‘default’ representation of the parameter.

  • undocumented (bool) – If true, hides the parameter from the command help.

  • last_option – If True, the parameter will set the posarg_only flag on the bound arguments.

Also available as clize.Parameter.

class clize.parser.ParameterWithSourceEquivalent(argument_name, **kwargs)[source]

Bases: clize.parser.Parameter

Parameter that relates to a function parameter in the source.

Parameters

argument_name (str) – The name of the parameter.

class clize.parser.HelperParameter(**kwargs)[source]

Bases: clize.parser.Parameter

Parameter that doesn’t appear in CLI signatures but is used for instance as the .sticky attribute of the bound arguments.

class clize.parser.ParameterWithValue(conv=<function identity at 0x7fd0fe54ec10>, default=<unset>, **kwargs)[source]

Bases: clize.parser.Parameter

A parameter that takes a value from the arguments, with possible default and/or conversion.

Parameters
  • conv (callable) – A callable to convert the value or raise ValueError. Defaults to identity.

  • default – A default value for the parameter or util.UNSET.

clize.parser.value_converter(func=None, *, name=None, convert_default=False)[source]

Callables decorated with this can be used as a value converter.

Parameters
  • name (str) –

    Use this name to designate the parameter value type.

    This should be in uppercase, with as few words as possible and no word delimiters.

    The default is the name of the decorated function or type, modified to follow this rule.

  • convert_default (bool) –

    If true, the value converter will be called with the default parameter value if none was supplied. Otherwise, the default parameter is used as-is.

    Make sure to handle None appropriately if you override this.

See Specifying a value converter.

class clize.parser.NamedParameter(aliases, **kwargs)[source]

Bases: clize.parser.Parameter

Equivalent of a keyword-only parameter in Python.

Parameters

aliases (sequence of strings) – The arguments that trigger this parameter. The first alias is used to refer to the parameter. The first one is picked as display_name if unspecified.

class clize.parser.FlagParameter(value, **kwargs)[source]

Bases: clize.parser.OptionParameter

A named parameter that takes no argument.

Parameters
  • value – The value when the argument is present.

  • false_value – The value when the argument is given one of the false value triggers using --param=xyz.

class clize.parser.OptionParameter(aliases, **kwargs)[source]

Bases: clize.parser.NamedParameter, clize.parser.ParameterWithValue, clize.parser.ParameterWithSourceEquivalent

A named parameter that takes an argument.

class clize.parser.IntOptionParameter(aliases, **kwargs)[source]

Bases: clize.parser.OptionParameter

A named parameter that takes an integer as argument. The short form of it can be chained with the short form of other named parameters.

class clize.parser.PositionalParameter(conv=<function identity at 0x7fd0fe54ec10>, default=<unset>, **kwargs)[source]

Bases: clize.parser.ParameterWithValue, clize.parser.ParameterWithSourceEquivalent

Equivalent of a positional-only parameter in Python.

class clize.parser.MultiParameter(min, max, **kwargs)[source]

Bases: clize.parser.ParameterWithValue

Parameter that can collect multiple values.

class clize.parser.ExtraPosArgsParameter(required=False, min=None, max=None, **kwargs)[source]

Bases: clize.parser.MultiParameter, clize.parser.PositionalParameter

Parameter that forwards all remaining positional arguments to the callee.

Used to convert *args-like parameters.

class clize.parser.AppendArguments(**kwargs)[source]

Bases: clize.parser.HelperParameter, clize.parser.MultiParameter

Helper parameter that collects multiple values to be passed as positional arguments to the callee.

Similar to ExtraPosArgsParameter but does not correspond to a parameter in the source.

class clize.parser.IgnoreAllArguments(**kwargs)[source]

Bases: clize.parser.HelperParameter, clize.parser.Parameter

Helper parameter for FallbackCommandParameter that ignores the remaining arguments.

class clize.parser.FallbackCommandParameter(func, **kwargs)[source]

Bases: clize.parser.NamedParameter

Parameter that sets an alternative function when triggered. When used as an argument other than the first all arguments are discarded.

class clize.parser.AlternateCommandParameter(func, **kwargs)[source]

Bases: clize.parser.FallbackCommandParameter

Parameter that sets an alternative function when triggered. Cannot be used as any argument but the first.

Exceptions

class clize.UserError(message)
class clize.errors.UserError(message)

An error to be displayed to the user.

If clize.run catches this error, the error will be printed without the associated traceback.

def main():
    raise clize.UserError("an error message")

clize.run(main)
$ python usererror_example.py
usererror_example.py: an error message

You can also specify other exception classes to be caught using clize.run’s catch argument. However exceptions not based on UserError will not have the command name displayed.

class clize.ArgumentError(message)
class clize.errors.ArgumentError(message)

An error related to argument parsing. If clize.run catches this error, the command’s usage line will be printed.

def main(i:int):
    if i < 0:
        raise clize.ArgumentError("i must be positive")

clize.run(main)
$ python argumenterror_example.py -- -5
argumenterror_example.py: i must be positive
Usage: argumenterror_example.py i

Help generation

clize.help manages the generation of help messages obtained using --help.

HelpCli is the command-line interface for it. It is injected as an extra alternate option by Clize. It can be replaced using Clize’s helper_class parameter.

HelpForClizeDocstring constructs the help for clize’s docstring format. It is invoked by HelpCli.get_help method. It can be swapped with the builder parameter of HelpCli.

It uses sigtools.specifiers.signature to obtain which functions document the parameters, elements_from_clize_docstring and helpstream_from_elements process the docstring so it can be fed to HelpForClizeDocstring.add_docstring.

clize.help.LABEL_POS = 'Arguments'

The label for positional parameters

clize.help.LABEL_OPT = 'Options'

The default label for named parameters

clize.help.LABEL_ALT = 'Other actions'

The label for alternate actions like --help

class clize.help.HelpForParameters(header, footer, sections, after) -> None[source]

Bases: object

Stores and displays help for a CLI with positional parameters, named parameters and/or alternate actions designated by a named parameter

Example output in relation to attribute names:

header

section:
    param1   Param1 description

After param2

    param2   Param2 description

footer
header = []

A list of strings representing paragraphs in the help header/description.

footer = []

A list of strings representing paragraphs in the help footer after everything else.

sections = OrderedDict("section_name" => OrderedDict("param_name" =>     (param, "description")))

Maps section names to parameters and their help.

after = {"param_name": ["paragraph"]}

Maps parameter names to additional paragraphs.

Method generated by attrs for class HelpForParameters.

classmethod blank_from_signature(signature)[source]

Creates a blank instance with placeholders for the parameters in signature.

The parameters are sorted into three sections:

LABEL_POS

Positional parameters

LABEL_OPT

Named parameters

LABEL_ALT

Alternate options (e.g. --help)

show_usage(name)[source]

Returns a summary overview of the command’s parameters.

Option parameters are collapsed as [OPTIONS] in the output.

usages()[source]

Returns an iterable of all possible complete usage patterns

show_full_usage(name)[source]

Returns an iterable of all possible complete usage patterns including the command name

show_help(name)[source]

Produce the full help.

clize.help.elements_from_clize_docstring(source)[source]

Converts a string to an iterable of element tuples such as (EL_FREE_TEXT, "text", False).

The result is suitable for helpstream_from_elements.

See below for which tuples are produced/understood.

clize.help.EL_LABEL = EL_LABEL

(EL_LABEL, "label")

Indicates that the subsequent EL_PARAM_DESC elements are under a section label.

clize.help.EL_FREE_TEXT = EL_FREE_TEXT

(EL_FREE_TEXT, "paragraph", is_preformatted)

Designates some free text. May be converted into header text, footer text, or additional paragraphs after a parameter depending on context.

The last free text elements at the end of a docstring are always considered to be the footer rather than additional paragraphs after a parameter.

is_preformatted is a boolean that indicates that the paragraph should not be reformatted.

clize.help.EL_PARAM_DESC = EL_PARAM_DESC

(EL_PARAM_DESC, "param", "paragraph")

Designates the description for a parameter.

clize.help.EL_AFTER = EL_AFTER

(EL_AFTER, "param", "paragraph", is_preformatted)

Explicitly designates an additional paragraph after a parameter. Unlike EL_FREE_TEXT, this cannot be confused for a footer paragraph.

clize.help.helpstream_from_elements(tokens)[source]

Transforms an iterable of non-explicit EL_* elements to an iterable of explicit HELP_* elements.

The result is suitable for HelpForClizeDocstring.add_helpstream.

clize.help.HELP_HEADER = HELP_HEADER

(HELP_HEADER, "paragraph", is_preformatted)

Designates a paragraph that appears before the parameter descriptions.

(HELP_FOOTER, "paragraph", is_preformatted)

Designates a paragraph that appears after the parameter descriptions.

clize.help.HELP_PARAM_DESC = HELP_PARAM_DESC

(HELP_PARAM_DESC, "param", "label", "paragraph")

Designates a parameter description. If no label was specified None should take its place.

clize.help.HELP_PARAM_AFTER = HELP_PARAM_AFTER

(HELP_PARAM_AFTER, "param", "paragraph", is_preformatted)

Designates a paragraph after a parameter description.

class clize.help.HelpForAutodetectedDocstring(*args, **kwargs)[source]

Bases: clize.help.HelpForParameters

Builds generic parameter help from the docstrings of Clize instances

Uses a custom docstring format. See clize docstring.

Method generated by attrs for class HelpForParameters.

classmethod from_subject(subject, owner)[source]

Constructs a HelpForClizeDocstring instance and populates it with data from a Clize instance.

It uses the parameters’ parser.Parameter.prepare_help and reads the docstrings of functions from which the parameters originate.

Parameters
  • subject (Clize) – The Clize instance to document.

  • owner (object) –

    The object of which subject is a member of, or None.

    This typically has a value if a CLI is defined as a class:

    class MyCli(object):
        @clize.Clize
        def cli(self, param):
            ...
    

    owner would refer to an instance of MyCli.

add_from_parameters(parameters)[source]

Uses parser.Parameter.prepare_help on an iterable of parameters

add_from_parameter_sources(subject)[source]

Processes the docstrings of the functions that have parameters in subject and adds their information to this instance.

Parameters

subject (Clize) – the Clize runner to document

add_docstring(docstring, name, pnames, primary)[source]

Parses and integrates info from a docstring to this instance.

Parameters
  • docstring (str) – The docstring to be read. Must be de-indented using something like inspect.cleandoc.

  • pnames (set) – If not None, only add info about these parameter names.

  • primary (bool) – Add headers and footers from this docstring.

parse_docstring(docstring)[source]

Alias of add_docstring for backwards compatibility.

add_helpstream(stream, pnames, primary)[source]

Add an iterable of tuples starting with HELP_ to this instance.

Parameters
  • stream (iterable) – An iterable of (HELP_*, ...) tuples, as produced by helpstream_from_elements

  • pnames (set) – If not None, only add info about these parameter names.

  • primary (bool) – Add headers and footers from this docstring.

class clize.help.HelpForClizeDocstring(*args, **kwargs)[source]

Bases: clize.help.HelpForAutodetectedDocstring

Method generated by attrs for class HelpForParameters.

add_docstring(docstring, name, pnames, primary)[source]

Parses a Clize docstring.

clize.help.document_from_sphinx_docstring(source, name)[source]

Reads a Sphinx.autodoc-compatible docstring into something helpstream_from_elements can process.

class clize.help.HelpForSphinxDocstring(*args, **kwargs)[source]

Bases: clize.help.HelpForClizeDocstring

Builds generic parameter help from the docstrings of Clize instances

Understands docstrings written for Sphinx’s autodoc.

Method generated by attrs for class HelpForParameters.

add_docstring(docstring, name, pnames, primary)[source]

Parses a Clize docstring.

class clize.help.HelpForSubcommands(usages, subcommands, header, footer) -> None[source]

Bases: object

Stores help for subcommand dispatchers.

subcommands

An ordered mapping of the subcommand names to their description.

header

Iterable of paragraphs for the help header.

footer

Iterable of paragraphs for the help footnotes.

Method generated by attrs for class HelpForSubcommands.

classmethod from_subject(subject, owner)[source]

Constructs a HelpForSubcommands instance and populates it with data from a Clize instance.

It uses the parameters’ parser.Parameter.prepare_help and reads the docstrings of functions from which the parameters originate.

Parameters
show_help(name)[source]

Produce the full help.

show_usage(name)[source]

Returns a summary overview of the dispatcher’s command format.

show_full_usage(name)[source]

Returns an iterable of all possible complete usage patterns for subcommands including the command name

usages()[source]

Returns an iterable of all possible complete usage patterns for all subcommands

class clize.help.HelpCli(subject, owner, builder=<bound method HelpForAutodetectedDocstring.from_subject of <class 'clize.help.HelpForAutodetectedDocstring'>>)[source]

Bases: object

A command-line interface for constructing and accessing the help and other meta-information about a CLI

cli(name: clize.parameters.pass_name, usage=False, *args: clize.Parameter.UNDOCUMENTED)[source]

Show the help

usage: Only show the full usage

get_help()[source]

Get the object

property description

A short description of this command

show(name)[source]

Legacy alias of get_help().show_help(...)

show_full_usage(name)[source]

Legacy alias of get_help().show_full_usage(...)

show_usage(name)[source]

Legacy alias of get_help().show_usage(...)

usages()[source]

Legacy alias of get_help().usages(...)

clize.help.ClizeHelp

alias of clize.help.HelpCli

Compability with older clize releases

clize.clize(fn=None, *, alias={}, force_positional=(), coerce={}, require_excess=False, extra=(), use_kwoargs=None)[source]

Compatibility with clize<3.0 releases. Decorates a function in order to be passed to clize.run. See Upgrading from clize 1 and 2.

clize.make_flag(source, names, default=False, type=None, help='', takes_argument=0)[source]

Compatibility with clize<3.0 releases. Creates a parameter instance. See Upgrading from clize 1 and 2.