Package: clargs
ClargsThe goal of theclargspackage is to create commandline interfaces from function signatures.Hit the ground running: With a single line, an existing function is turned into a command line programExtensible: It is flexible enough to do everything thatargparsedoes, and keeps you in controlNo magic: All the extension does is call commands inargparse; you can log and see these commandsSafe: The built-in pythonargparsemodule does all the work, so safety guarantees from that module applyTyping: Parameter types are set asPEP 484type hints (e.g.def foo(bar: int))Standard: By usingargparse, you get standard behaviour such as long/short parameters, combine flags, help functionDon't repeat yourself: Every parameter is defined (changed, added, removed) in one spot and only one spot, the function definitionRich parameter types: Support forstr,int,float,bool,pathlib.Pathandtyping.Literal(multiple-choice values)Richer parameter types: In addition, lists of these parameters are allowed, default values, boolean-flags (--foo/--no-foo), countsSimple: Pure python, no dependenciesDocumentation: Function's docstring creates--helpdocumentation. Support forSphynx,GoogleDoc,NumpyDoc,EpyTextExampleCheck out thelist of examplesto see the package in actionA quick example (just to get you excited):importclargsdefcount(singular:str,plural:str,maxitems:int=10,*,shout:bool=False,):"""Counts from 1 to given number (default = 10)This text should not appear@param singular: The singular form of the thing to count@param plural: The plural form of the thing to count@param maxitems: The number to count to@param shout: If True, will convert all expressions to capitals"""foriinrange(maxitems):text=f"{i+1}{singularifi==0elseplural}"ifshout:text=text.upper()print(text)if__name__=="__main__":clargs.create_parser_and_run(count)> python main.py --helpusage: main.py [-h] [--shout [SHOUT]] singular plural [maxitems]Counts from 1 to given number (default = 10)positional arguments:singular              The singular form of the thing to countplural                The plural form of the thing to countmaxitems              The number to count tooptions:-h, --help            show this help message and exit--shout [SHOUT], -s [SHOUT]If True, will convert all expressions to capitals> python main.py bottle bottles1 bottle2 bottles3 bottles4 bottles5 bottles6 bottles7 bottles8 bottles9 bottles10 bottles> python main.py bottle bottles 5 --shout=yes1 BOTTLE2 BOTTLES3 BOTTLES4 BOTTLES5 BOTTLESSupported typesThe type of the parameter (given through a type-hint) determines what the input is parsed at.
If no type-hint is given,stris assumed.str,int,float,pathlib.PathThese types just call the constructor on the string (e.g.python main.py --input-file /tmp/myfile.txt --repeat 5will assignpathlib.Path("/tmp/myfile.txt")toinput_fileandint("5")torepeat(assuming a function signature like:def run(*, input_file: pathlib.Path, repeat: int)).boolBooleans need some special work internally (sincebool("False") == True). Any parameter of typeboolwill acceptYes,No,TrueandFalse(case-insensitive) as values.
Booleans can also be madeFlags, see below under "Extra Types".typing.Literal["foo", "bar", "baz"]Usingtyping.Literalparameters can be made that can only have certain values.
The type of the parameters can be any of the types abovelist[X]ortyping.Sequence[X]Lists of items is supported (for all pf the above types). For instance a signature ofdef sum(*, terms: typing.List[float]) -> floatmeans you can usepython sum.py --terms 1.2 4 -5typing.Optional[X]andNone | Xtyping.Optionalor a union withNoneis ignored, so this won't affect the command line signature.Extra TypesIn addition to normal types, theclargspackage defines some special types.clargs.FlagIs an alias forbool(should be recognised by static type-checkers).
Creates--foo/--no-fooparameter pair to control booleansclargs.CountIs an alias forint(should be recognised by static type-checkers).
Counts how often a parameter is present (mostly used in--verbose --verbose --verboseparameters)Custom TypeI hope to add types quickly in future versions.In the meantime, any type not listed here will also work as long as an explicit conversion function is defined.SubparsersUsing subparsers it's possible to add multiple functions to your cli. Seean example hereDebug outputclargsuses python'sloggingmodule to log toDEBUGlevel exactly what is being added toargparse'sadd_argument()function.
By making the logger output this to screen, you can debug what's going on.Seean example hereGlobal SettingsYou can control settings on howclargsworks, by using theclargs.Clargsclass to call your functions.myclargs = clargs.Clargs(clargs.Settings(...))
myclargs.create_parser_and_run(func)You can use the following settings (as keyword arguments toSettings)flag_prefix(default--)If you want another flag prefix (e.g.++or/for windows-like flags), set this here.
If you provide your own parser (i.e. you don't usecreate_parser()on theClargsobject), you need to make sure you setprefix_charscorrectly on the parser.short_flag_prefix(default-)Same but for the short flagsgenerate_short_flags(defaultTrue)If true, short flags are generated (so you can use-finstead of--foo.
Note that the short flag is only generated for the first parameter starting with a certain letter.positional_and_kw_args_become(defaultpositional)Python functions can have positional-only arguments (anything before/), keyword-only arguments (anything after*), and arguments that can be used both positionally and as keywords (default).
Positional-only arguments always become positional commandline arguments. Keyword-only arguments always become keyword commandline arguments (flags).
This parameter determines what to do with arguments that can be both positional and keyword.positionalthose arguments are rendered as positional commandline argumentsflagthose arguments are rendered as keyword commandline arguments (flags)flag_if_defaultthose arguments are rendered as flags if they have a default value, else as positional commandline arguments.replace_underscore_with_dash(defaultTrue)If false, underscores are not replaced with dashes for the commandline arguments.
In the default behaviour, a function parameterfoo_barwill become a flag--foo-bar. If this parameter is false, it becomes--foo_bar.This only affects keyword parameters (flags), and subparser commands (so if a subparser is created for the functioncount_down, then the commandline command will becount-down.Compare to other solutionsThere are many other solutions to create command line interfaces from functions.
I don't think it makes sense to create a comparison list of features now, only to have it be not up to date anymore tomorrow.The reasons that I developedclargsis because I could not find any solution that made me happy (based on the features and properties I describe above).