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.
parameters()[source]

Returns the parameters used to instantiate this class, minus the wrapped callable.

classmethod keep(fn=None, **kwargs)[source]

Instead of wrapping the decorated callable, sets its cli attribute to a Clize instance. Useful if you need to use the decorator but must still be able to call the function regularily.

classmethod as_is(obj=None, *, description=None, usages=None)[source]

Returns a CLI object which uses the given callable with no translation.

The following parameters improve the decorated object’s compatibility with Clize’s help output:

Parameters:
  • description – A description for the command.
  • usages – A list of usages for the command.
classmethod get_cli(obj, **kwargs)[source]

Makes an attempt to discover a command-line interface for the given object.

The process used is as follows:

  1. If the object has a cli attribute, it is used with no further transformation.
  2. If the object is callable, Clize or whichever object this class method is used from is used to build a CLI. **kwargs are forwarded to its initializer.
  3. If the object is iterable, SubcommandDispatcher is used on the object, and its cli method is used.

Most notably, clize.run uses this class method in order to interpret the given object(s).

cli

Returns the object itself, in order to be selected by get_cli

helper[source]

A cli object(usually inherited from help.Help) when the user requests a help message. See the constructor for ways to affect this attribute.

signature[source]

The parser.CliSignature object used to parse arguments.

read_commandline(args)[source]

Reads the command-line arguments from args and returns a tuple with the callable to run, the name of the program, the positional and named arguments to pass to the callable.

Raises:ArgumentError
class clize.SubcommandDispatcher(commands=(), description=None, footnotes=None)[source]
clizer

alias of Clize

cli[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.

classmethod from_signature(sig, extra=(), **kwargs)[source]

Takes a signature object and returns an instance of this class deduced from it.

Parameters:
  • sig (inspect.Signature) – The signature object to use.
  • extra (iterable) – Extra parameter instances to include.
classmethod convert_parameter(param)[source]

Convert a Python parameter to a CLI parameter.

read_arguments(args, name)[source]

Returns a CliBoundArguments instance for this CLI signature bound to the given arguments.

Parameters:
  • args (sequence) – The CLI arguments, minus the script name.
  • name (str) – The script name.
clize.parser.parameter_converter(obj)[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(*, pos=<function unimplemented_parameter at 0x7fbca05b0950>, varargs=<function unimplemented_parameter at 0x7fbca05b0950>, named=<function unimplemented_parameter at 0x7fbca05b0950>, varkwargs=<function unimplemented_parameter at 0x7fbca05b0950>, 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:
  • 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={})[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.
class clize.parser.CliBoundArguments(sig, args, name)[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.

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.

unsatisfied = set(<required parameters>)

Required parameters that haven’t yet been satisfied.

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.

LAST_OPTION = clize.Parameter.LAST_OPTION

Annotate a parameter with this and all following arguments will be processed as positional.

IGNORE = clize.Parameter.IGNORE

Annotate a parameter with this and it will be dropped from the resulting CLI signature.

UNDOCUMENTED = clize.Parameter.UNDOCUMENTED

Parameters annotated with this will be omitted from the documentation (--help).

REQUIRED = clize.Parameter.REQUIRED

Annotate a parameter with this to force it to be required.

Mostly only useful for *args parameters. In other cases, simply don’t provide a default value.

required = False

Is this parameter required?

is_alternate_action = False

Should this parameter appear as an alternate action or as a regular parameter?

extras = ()

Iterable of extra parameters this parameter incurs

display_name = None

The name used in printing this parameter.

undocumented = None

If true, this parameter is hidden from the documentation.

last_option = None

If true, arguments after this parameter is triggered will all be processed as positional.

read_argument(ba, i)[source]

Reads one or more arguments from ba.in_args from position i.

Parameters:
apply_generic_flags(ba)[source]

Called after read_argument in order to set attributes on ba independently of the arguments.

Parameters:ba (clize.parser.CliBoundArguments) – The bound arguments object this call is expected to mutate.

The base implementation of this method applies the last_option setting if applicable and discards itself from CliBoundArguments.unsatisfied

unsatisfied(ba)[source]

Called after processing arguments if this parameter required and not discarded from CliBoundArguments.unsatisfied.

post_parse(ba)[source]

Called after all arguments are processed successfully.

get_all_names()[source]

Return a string with all of this parameter’s names.

get_full_name()[source]

Return a string that designates this parameter.

show_help(desc, after, f, cols)[source]

Called by ClizeHelp to produce the parameter’s description in the help output.

show_help_parens()[source]

Return a string to complement a parameter’s description in the --help output.

help_parens()[source]

Return an iterable of strings to complement a parameter’s description in the --help output. Used by show_help_parens

prepare_help(helper)[source]

Called by ClizeHelp to allow parameters to complement the help.

Param:clize.help.ClizeHelp helper: The object charged with displaying the help.
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 0x7fbca05ae048>, 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.
conv = None

The function used for coercing the value into the desired format or type.

default = None

The default value used for the parameter, or util.UNSET if there is no default value. Usually only used for displaying the help.

required

Tells if the parameter has no default value.

coerce_value(arg, ba)[source]

Coerces arg using the conv function. Raises errors.BadArgumentFormat if the coercion function raises ValueError.

get_value(ba, i)[source]

Retrieves the “value” part of the argument in ba at position i.

help_parens()[source]

Shows the default value in the parameter description.

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

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

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.
aliases = None

The parameter’s aliases, eg. “–option” and “-o”.

classmethod alias_key(name)[source]

Sort key function to order aliases in source order, but with short forms(one dash) first.

get_all_names()[source]

Retrieves all aliases.

short_name

Retrieves the shortest alias for displaying the parameter signature.

get_full_name()[source]

Uses the shortest name instead of the display name.

redispatch_short_arg(rest, ba, i)[source]

Processes the rest of an argument as if it was a new one prefixed with one dash.

For instance when -a is a flag in -abcd, the object implementing it will call this to proceed as if -a -bcd was passed.

get_value(ba, i)[source]

Fetches the value after the = (--opt=val) or in the next argument (--opt val).

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.
required = False
false_triggers = ('0', 'n', 'no', 'f', 'false')

Values for which --flag=X will consider the argument false and will pass false_value to the function. In all other cases value is passed.

value = None

The value passed to the function if the flag is triggered without a specified value.

read_argument(ba, i)[source]

Overrides NamedParameter‘s value-getting behavior to allow no argument to be passed after the flag is named.

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

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

A named parameter that takes an argument.

read_argument(ba, i)[source]

Stores the argument in CliBoundArguments.kwargs if it isn’t already present.

format_type()[source]

Returns a string designation of the value type.

format_argument(long_alias)[source]
get_all_names()[source]

Appends the value type to all aliases.

get_full_name()[source]

Appends the value type to the shortest alias.

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.

read_argument(ba, i)[source]

Handles redispatching after a numerical value.

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

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

Equivalent of a positional-only parameter in Python.

read_argument(ba, i)[source]

Stores the argument in CliBoundArguments.args.

help_parens()[source]

Puts the value type in parenthesis since it isn’t shown in the parameter’s signature.

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

Bases: clize.parser.ParameterWithValue

Parameter that can collect multiple values.

min = None

The minimum amount of values this parameter accepts.

max = None

The maximum amount of values this parameter accepts.

required

Returns if there is a minimum amount of values required.

get_collection(ba)[source]

Return an object that new values will be appended to.

read_argument(ba, i)[source]

Adds passed argument to the collection returned by get_collection.

apply_generic_flags(ba)[source]

Doesn’t automatically mark the parameter as satisfied.

unsatisfied(ba)[source]

Lets errors.MissingRequiredArguments be raised or raises errors.NotEnoughValues if arguments were passed but not enough to meet min.

get_full_name()[source]

Adds an elipsis to the parameter name.

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.

get_collection(ba)[source]

Uses CliBoundArguments.args to collect the remaining arguments.

apply_generic_flags(ba)[source]

Sets itself as sticky parameter so that errors.TooManyArguments is not raised when processing further 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.

get_collection(ba)[source]

Uses CliBoundArguments.args to collect the remaining arguments.

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

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

Helper parameter for FallbackCommandParameter that ignores the remaining arguments.

read_argument(ba, i)[source]

Does nothing, ignoring all arguments processed.

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.

is_alternate_action = True
func = None

The function that will be called if this parameter is mentionned.

description[source]

Use func‘s docstring to provide the parameter description.

read_argument(ba, i)[source]

Clears all processed arguments, sets up func to be called later, and lets all remaining arguments be collected as positional if this was the first argument.

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.

read_argument(ba, i)[source]

Raises an error when this parameter is used after other arguments have been given.

Exceptions

exception clize.errors.UserError[source]

Bases: ValueError

An error to be printed to the user.

exception clize.errors.ArgumentError(message=None)[source]

Bases: clize.errors.UserError

An error related to the arguments passed through the command-line interface

exception clize.errors.MissingRequiredArguments(missing)[source]

Bases: clize.errors.ArgumentError

Raised when required parameters have not been provided an argument

exception clize.errors.TooManyArguments(extra)[source]

Bases: clize.errors.ArgumentError

Raised when too many positional arguments have been passed for the parameters to consume.

exception clize.errors.DuplicateNamedArgument(message=None)[source]

Bases: clize.errors.ArgumentError

Raised when a named option or flag has been passed twice.

exception clize.errors.UnknownOption(name)[source]

Bases: clize.errors.ArgumentError

Raised when a named argument has no matching parameter.

exception clize.errors.MissingValue(message=None)[source]

Bases: clize.errors.ArgumentError

Raised when an option received no value.

exception clize.errors.NotEnoughValues(message=None)[source]

Bases: clize.errors.ArgumentError

Raised when MultiOptionParameter is given less values than its min parameter.

exception clize.errors.TooManyValues(message=None)[source]

Bases: clize.errors.ArgumentError

Raised when MultiOptionParameter is given more values than its max parameter.

exception clize.errors.CliValueError[source]

Bases: ValueError

Specialization of ValueError for showing a message to the user along with the error rather than just the incorrect value.

exception clize.errors.BadArgumentFormat(text)[source]

Bases: clize.errors.ArgumentError

Raised when an argument cannot be converted to the correct format.

exception clize.errors.ArgsBeforeAlternateCommand(param)[source]

Bases: clize.errors.ArgumentError

Raised when there are arguments before a non-fallback alternate command.

class clize.errors.SetErrorContext(exc_type, **attributes)[source]

Bases: object

Context manager that sets attributes on exceptions that are raised past it

Parameters:
  • exc_type – The exception type to operate on.
  • attributes – The attributes to set on the matching exceptions. They will only be set if yet unset on the exception.

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.