Package: autoclick
AutoClickAutoClick creates Click-based CLIs using type annotations.The simplest use of AutoClick requires annotating your main method with@autoclick.command:# test.pyimportautoclick@autoclick.command("greet")defmain(greeting:str,name:str):print(f"{greeting}{name}")if__name__=="__main__":main()$pythontest.py--help
Usage:test.py[OPTIONS][GREETING][NAME]Options:--helpShowthismessageandexit.For additional customization, keyword arguments can be passed to the command decorator:importautoclick@autoclick.command(short_names={"greeting":"G","name":"n"},show_defaults=True)defmain(greeting:str="hello",name:str="human"):print(f"{greeting}{name}")$pythontest.py--help
Usage:test.py[OPTIONS]Options:-G,--greetingTEXT[default:hello]-n,--nameTEXT[default:human]--helpShowthismessageandexit.Type conversionIn Click, type conversion can be done either in a callback or by using a callable type (such as a subclass of ParamType) as the type. In AutoClick, type conversions are performed automatically based on type annotations for callable types. However, for more complex type conversion, there are three additional methods:Automatic conversion functions. A conversion function is decorated by@conversion. The conversion decorator by default infers the type being converted to from the return annotation. Otherwise, the destination type can be specified as an argument to the decorator. The decorator registers the function as the converter for the specified type. When that type is encountered as an annotation of a parameter to a command function, the converter function is used to convert the string argument to that type.importautoclickclassBork:def__init__(self,n:int):self.n=ndef__str__(self):print(",".join(["bork"]*self.n))@autoclick.conversion()defbork(n:int)->Bork:returnBork(n)@autoclick.command("bork")defmain(b:Bork):print(b)In the case where there needs to be specialized handling of common types, new types can be created usingtyping.NewType:importautoclickimporttypingDoubleInt=typing.NewType("DoubleInt",int)@autoclick.conversion(DoubleInt)defdouble_int(i:str):returnint(i)*2@autoclick.command("double")defmain(i1:int,i2:DoubleInt):print(i1,i2)Conversion functions can also be specified explicitly in the command decorator:importautoclick@autoclick.command(types={"a":double_int})defmain(a:int):print(a)Note that any of the types in theclick.Typespackage can also be used in this way.For composite types, theautoclick.composite_typeandautoclick.composite_factoryfunctions can be used. An example of a composite type is a class that requires more than one parameter to its constructor. For composite types, the same annotation-based CLI creation is performed, and the parameters are injected into the CLI in place of the composite parameter.importautoclick@autoclick.composite_type()classFoo:def__init__(self,bar:str,baz:int):self.bar=barself.baz=baz@autoclick.command()defmain(foo:Foo):print(foo.bar,foo.baz)In this case, the options to main would be--foo-barand--foo-baz. Once the CLI is processed, the values of these options are used to construct theFooinstance, which is then passed to the call tomain. The parameter name in the command function is prepended to the parameter names of the composite type, so that a composite type can be used multiple types in a command function signature.Aautoclick.composite_factoryfunction returns a complex type. For example, the code below is equivalent to the code above:importautoclickclassFoo:def__init__(self,bar:str,baz:int):...@autoclick.composite_factory(Foo)deffoo_factory(bar:str,baz:int):returnFoo(bar,baz)Conditionals and ValidationsConditionals and Validations are similar - they are both decorators that take**kwargsparameter. The keywords are parameter names and values are parameter values. When the function takes multiple parameters, they should specify the order; ordering depends on python 3.5+ behavior that dictionaries are ordered implicitly.A conditional function is used to modify the values of one or more parameters conditional on the value(s) of other parameters. A conditional function may return a dict with keys being parameter names that should be updated, and values being the new parameter values.A validation function is intended to check that one or more parameter values conform to certain restrictions. The return value of a validation function is ignored.Both conditional and validation functions can throw ValidationError.These functions can be associated with parameters in two ways. First, using theconditionalsandvalidationsarguments of the command decorator. These are dicts with a parameter name or tuple of parameter names being the key and the function being the value. Second, validation functions can be associated with parameters when they are decorated with@autoclick.validationand the parameter type matches the type argument of the validation decorator. Multi-parameter validations can only be associated via the first method. Since conditionals are expected to be multi-valued, there is no@autoclick.conditionalannotation, i.e. they must always be explicitly specified.Type matchingYou can also use distinct types created by thetyping.NewTypefunction for type matching validations. For example, if you want to define a parameter that must be positive and even:importautoclickfromtypingimportNewTypePositiveEven=NewType('PositiveEven',int)@autoclick.validation(PositiveEven)defvalidate_positive_even(arg:int):ifarg<0:raiseautoclick.ValidationError()ifarg%2!=0:raiseautoclick.ValidationError()Note that the typing library does not currently provide an intersection type. Thus, Positive, Even, and PositiveEven must all be distinct validations. There are two ways to simplify:Add the parameter to the validation dict of the command decorator with a tuple of mutliple functions as the value:importautoclick@autoclick.command(validations={"a":positive,even})Create a composite validation:importautoclick@autoclick.validation(PositiveEven,(positive,even))defvalidate_positive_even(arg:int):passor evenimportautoclickautoclick.validation(PositiveEven,(positive,even))Docstring utilizationAutoClick uses thedocparselibrary to parse the docstrings of command functions and composites to extract help text. Note that currently docparse only supports Google-style docstrings.# test.pyimportautoclick@autoclick.command(show_defaults=True)defmain(x:str="hello"):"""Print a stringArgs:x: The string to print."""print(x)if__name__=="__main__":main()$pythontest.py--help
Usage:test.py[OPTIONS][X]Printastring

Options:-x,--xTEXTThestringtoprint.[default:hello]--helpShowthismessageandexit.GroupsAutoClick CLIs can have multiple subcommands, by creating command groups:fromautoclickimportgroup@group("myprog")defmyprog():pass@myprog.command("hi")defsay_hi(name:str):print(f"hello{name}")@myprog.command("bye")defsay_bye(name:str):print(f"byebye{name}")AutoClick provides alternative group types. For example,DefaultAutoClickGroupcan take a default command name to run when a command is not specified:fromautoclickimportgroupfromautoclick.commandsimportDefaultAutoClickGroup@group("myprog",group_class=DefaultAutoClickGroup,default="hello")defmyprog():pass# This command is run by default if the command name is not specifieddefhello(name:str):print(f"hi{name}")Installation$pipintallautoclickRuntime DependenciesPython 3.6+docparseBuild dependenciespoetry 0.12+pytest (with pytest-cov plugin)DetailsOption attribute inferenceThe following sections describe details of how the arguments to click classes/functions are inferred from the type and docstring information:All Parametersname (long): parameter name; underscores converted to dashes unless keep_underscores=True in the command decorator.name (short): starting from the left-most character of the parameter name, the first character that is not used by another parameter or by any built-in; can be overridden by specifying the 'parameter_names' dictionary in the command decorator.type: inferred from the type hint; if type hint is missing, inferred from the default value; if default value is missing, str.required: by default, true for positional arguments (Arguments) and false for keyword arguments (Options); if positionals_as_options=True in the command decorator, positional arguments are instead required Options. Required keyword arguments can be specified in the 'required' list in the command decorator.default: unset for positional arguments, keyword value for keyword arguments.nargs: 1 unless type is Tuple (in which case nargs is the number of arguments to the Tuple).Option-onlyhide_input: False unless the command 'hidden' parameter is specified and includes the parameter name.is_flag: True for keyword arguments of type boolean; assumed to be the True option unless the name starts with 'no'; the other option will always be inferred by adding/removing 'no-'multiple: True for sequence typeshelp: Parsed from docstring.TodoDocumentation for positional arguments (see)Handle return values (e.g. if a int, treat as a return code; if a dict, convert to JSON and write to stdout, etc)Look at incorporating features from contributed packages: