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.
  • pass_name (bool) – Pass the command name as first argument to the wrapped function.
  • 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.
classmethod as_is(obj)[source]

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

cli

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

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).

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.

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.

parameters()[source]

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

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
signature[source]

The parser.CliSignature object used to parse arguments.

class clize.SubcommandDispatcher(commands=(), description=None, footnotes=None)[source]
cli(self, name, command:(<operator.methodcaller object at 0xf5ae10cc>, clize.Parameter.LAST_OPTION), *args)[source]
clizer

alias of Clize

Help

class clize.help.Help(subject, owner)[source]
prepare()[source]

Override for stuff to be done once per subject

prepare_once()[source]
cli(<self>, name, *args:clize.Parameter.UNDOCUMENTED, usage=False)[source]

Show the help

usage: Only show the full usage

class clize.help.ClizeHelp(subject, owner)[source]
signature
classmethod get_param_type(param)[source]
prepare()[source]
argdoc_re = <_sre.SRE_Pattern object>
description
show_usage(name)[source]
alternates_with_helper()[source]
usages(name)[source]
show_full_usage(name)[source]
show_arguments()[source]
show_argument(param, desc, after, f, cols)[source]
show(name)[source]
class clize.help.DispatcherHelper(subject, owner)[source]
show_commands()[source]
prepare_notes(doc)[source]
prepare()[source]
show(name)[source]
show_usage(name)[source]
subcommands_with_helper()[source]
usages(name)[source]
show_full_usage(name)[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.
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 Parameter instances.

required = set()

A set of all required parameters.

converter(param, annotations) = <functools.partial object>
param_cls

The parameter class from_signature will use to convert source parameters to CLI parameters

alias of Parameter

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

Takes a signature object and returns an instance of this class derived 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='unnamed')[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.
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.

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:

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.Parameter(display_name, undocumented=False, last_option=None)[source]

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
required = False

Is this parameter required?

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.

LAST_OPTION = clize.Parameter.LAST_OPTION

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

UNDOCUMENTED = clize.Parameter.UNDOCUMENTED

Parameters annotated with this will be omitted from the documentation.

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.
format_type()[source]
full_name[source]
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.ParameterWithValue(typ=<function identity at 0xf5a9fd14>, default=<unset>, **kwargs)[source]

Bases: clize.parser.Parameter

A parameter that stores a value, with possible default and/or conversion.

Parameters:
  • typ (callable) – A callable to convert the value or raise ValueError. Defaults to util.identity.
  • default – A default value for the parameter or util.UNSET.
required

Tells if the parameter has no default value.

coerce_value(arg)[source]

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

format_type()[source]
full_name[source]
class clize.parser.PositionalParameter(typ=<function identity at 0xf5a9fd14>, default=<unset>, **kwargs)[source]

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

Equivalent of a positional-only parameter in python.

read_argument(ba, i)[source]
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.
classmethod alias_key(name)[source]

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

full_name[source]
redispatch_short_arg(rest, ba, i)[source]

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

get_value(ba, i)[source]
class clize.parser.FlagParameter(value, false_value, **kwargs)[source]

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

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.
false_triggers = ('0', 'n', 'no', 'f', 'false')
read_argument(ba, i)[source]
is_flag_activation(arg)[source]

Checks if an argument triggers the true or false value.

format_type()[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]
format_type()[source]
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]
class clize.parser.MultiParameter(typ=<function identity at 0xf5a9fd14>, default=<unset>, **kwargs)[source]

Bases: clize.parser.ParameterWithValue

Parameter that can collect multiple values.

get_collection(ba)[source]

Return an object that new values will be appended to.

read_argument(ba, i)[source]
class clize.parser.EatAllPositionalParameter(typ=<function identity at 0xf5a9fd14>, default=<unset>, **kwargs)[source]

Bases: clize.parser.MultiParameter

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

get_collection(ba)[source]
class clize.parser.EatAllOptionParameterArguments(param, **kwargs)[source]

Bases: clize.parser.EatAllPositionalParameter

Helper parameter for .EatAllOptionParameter that adds the remaining arguments as positional arguments for the function.

class clize.parser.IgnoreAllOptionParameterArguments(param, **kwargs)[source]

Bases: clize.parser.EatAllOptionParameterArguments

Helper parameter for .EatAllOptionParameter that ignores the remaining arguments.

read_argument(ba, i)[source]
class clize.parser.EatAllOptionParameter(**kwargs)[source]

Bases: clize.parser.NamedParameter

Parameter that collects all remaining arguments as positional arguments, even those which look like named arguments.

extra_type

alias of EatAllOptionParameterArguments

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

Bases: clize.parser.EatAllOptionParameter

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

description[source]
get_collection(ba)[source]
read_argument(ba, i)[source]
class clize.parser.AlternateCommandParameter(func, **kwargs)[source]

Bases: clize.parser.FallbackCommandParameter

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

read_argument(ba, i)[source]
class clize.parser.ExtraPosArgsParameter(required=False, **kwargs)[source]

Bases: clize.parser.PositionalParameter

Parameter that forwards all remaining positional arguments to the callee.

required = None
read_argument(ba, i)[source]

Exceptions

exception clize.errors.UserError[source]

Bases: exceptions.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.BadArgumentFormat(typ, val)[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=<type 'bool'>, help='', takes_argument=0)[source]

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