Package: radicli
radicli: Radically lightweight command-line interfacesradicliis a small, zero-dependency Python package for creating command line interfaces, built on top of Python'sargparsemodule. It introduces minimal overhead, preserves your original Python functions and usestype hintsto parse values provided on the CLI. It supports all common types out-of-the-box, including complex ones likeList[str],LiteralandEnum, and allows registeringcustom typeswith custom converters, as well as custom CLI-onlyerror handling, exporting astatic representationfor faster--helpand errors and auto-generatedMarkdown documentation.Important note:This package aims to be a simple option based on the requirements of our libraries. If you're looking for a more full-featured CLI toolkit, check outtyper,clickorplac.⏳ InstallationNote thatradiclicurrently requiresPython 3.8+.pipinstallradicli👩‍💻 UsageTheRadicliclass sets up the CLI and provides decorators for commands and subcommands. TheArgdataclass can be used to describe how the arguments should be presented on the CLI. Types and defaults are read from the Python functions. You typically don't have to change anything about how you implement your Python functions to make them available as a CLI command.# cli.pyfromradicliimportRadicli,Argcli=Radicli()@cli.command("hello",name=Arg(help="Your name"),age=Arg("--age","-a",help="Your age"),greet=Arg("--greet","-G",help="Whether to greet"),)defhello(name:str,age:int,greet:bool=False):"""Description of the function for help text."""ifgreet:print(f"Hello{name}({age})!")if__name__=="__main__":cli.run()$ python cli.py hello Alex --age 35 --greet
Hello Alex (35)!If a file only specifies asingle command(with or without subcommands), you can optionally leave out the
command name. So the above example script can also be called like this:$ python cli.py Alex --age 35 --greet
Hello Alex (35)!Alternatively, you can also useRadicli.call:# cli.pyfromradicliimportRadicli,Argdefhello(name:str,age:int):print(f"Hello{name}({age})!")if__name__=="__main__":args=dict(name=Arg(help="Your name"),age=Arg("--age","-a",help="Your age"))command=Command.from_function("hello",args,hello)Radicli().call(command)$ python cli.py Alex --age 35
Hello Alex (35)!Subcommandsradiclisupports one level of nested subcommands. The parent command may exist independently, but it doesn't have to.@cli.subcommand("parent","child1",name=Arg("--name",help="Your name"))defparent_child1(name:str):...@cli.subcommand("parent","child2",name=Arg("--age",help="Your age"))defparent_child2(age:int):...$ python cli.py parent child1 --name Alex
$ python cli.py parent child2 --age 35Working with typesFor built-in callable types likestr,intorfloat, the string value received from the CLI is passed to the callable, e.g.int(value). More complex, nested types are resolved recursively. The library also provides several built-incustom typesfor handling things like file paths.⚠️ Note that there's a limit to what can reasonably be supported by a CLI interface so it's recommended to avoid overly complex types. For aUniontype, thefirsttype of the union is used.Optionaltypes are expected to be left unset to default toNone. If a value is provided, the type marked as optional is used, e.g.strforOptional[str].ListsBy default, list types are implemented by allowing the CLI argument to occur more than once. The value of each element is parsed using the type defined for list members.@cli.command("hello",fruits=Arg("--fruits",help="One or more fruits"))defhello(fruits:List[str]):print(fruits)$ python cli.py hello --fruits apple --fruits banana --fruits cherry
['apple', 'banana', 'cherry']If you don't like this syntax, you can also add aconverterto theArgdefinition that handles the value differently, e.g. by splitting a comma-separated string. This would let the user write--fruits apple,banana,cherry, while still passing a list to the Python function.Literals and EnumsArguments that can only be one of a given set of values can be typed as aLiteral. Any values not in the list will raise a CLI error.@cli.command("hello",color=Arg("--color",help="Pick a color"))defhello(color:Literal["red","blue","green"]):print(color)# this will be a stringEnums are also supported and in this case, the enum key can be provided on the CLI and the function receives the selected enum member.classColorEnum(Enum):red="the color red"blue="the color blue"green="the color green"@cli.command("hello",color=Arg("--color",help="Pick a color"))defhello(color:ColorEnum):print(color)# this will be the enum, e.g. ColorEnum.redUsing custom types and convertersradiclisupports defining custom converter functions to handle individual arguments, as well as all instances of a given type globally. Converters take the string value provided on the CLI and should return the value passed to the function, consistent with the type. They can also raise validation errors.format_name=lambdavalue:value.upper()@cli.command("hello",name=Arg("--name",converter=format_name))defhello(name:str):print(f"Hello{name}"!)$ python cli.py hello --name Alex
Hello ALEX!Global converters for custom typesTheconvertersargument lets you provide a dict of types mapped to converter functions when initializingRadicli. If an argument of that target type is encountered, the input string value is converted automatically. This ensures your Python functions remain composable and don't need additional logic only to satisfy the CLI usage.The following example shows how to register a custom converter that loads aspaCypipeline from a string name, while allowing the function itself to require theLanguageobject itself:importradicliimportspacydefload_spacy_model(name:str)->spacy.language.Language:returnspacy.load(name)converters={spacy.language.Language:load_spacy_model}cli=Radicli(converters=converters)@cli.command("process",nlp=Arg(help="The spaCy pipeline to use"),name=Arg("--text",help="The text to process"))defprocess_text(nlp:spacy.language.Language,text:str):doc=nlp(text)print(doc.text,[token.pos_fortokenindoc])$ python test.py process en_core_web_sm --text Hello world!
Hello world! ['INTJ', 'NOUN', 'PUNCT']If you want to alias an existing type to add custom handling for it, you can create aNewType. This is also how the built-inPathconvertersare implemented. In help messages, the type it is based on will be displayed together with the custom name.fromtypingimportNewTypefrompathlibimportPathExistingPath=NewType("ExistingPath",Path)defconvert_existing_path(path_str:str)->Path:path=Path(path_str)ifnotpath.exists():raiseValueError(f"path does not exist:{path_str}")returnpathconverters={ExistingPath:convert_existing_path}For generic types that can have arguments, e.g.ListandList[str], the converters are checked for both the exact type, as well as the origin. This means you can have multiple converters for different generics, as well as a fallback:converters = {
    List[str]: convert_string_list,
    List[int]: convert_int_list,
    List: convert_other_lists,
}Allowing extra argumentsIf you want to capture and consume extra arguments not defined in the function and argument annotations, you can use thecommand_with_extraorsubcommand_with_extradecorators. Extra arguments are passed to the function as a list of strings to an argument_extra(which you can change via theextra_keysetting when initializing the CLI). spaCy uses this feature to pass settings topipin itsdownloadcommandor to allow arbitraryconfiguration overridesduring training.@cli.command_with_extra("hello",name=Arg("--name",help="Your name"))defhello(name:str,_extra:List[str]=[]):print(f"Hello{name}!",_extra)$ python cli.py hello --name Alex --age 35 --color blue
Hello Alex! ['--age', '35', '--color', 'blue']Command aliases by stacking decoratorsThe command and subcommand decorators can be stacked to make the same function available via different command aliases. In this case, you just need to make sure that all decorators receive the same argument annotations, e.g. by moving them out to a variable.args=dict(name=Arg(help="Your name"),age=Arg("--age","-a",help="Your age"))@cli.command("hello",**args)@cli.command("hey",**args)@cli.subcommand("greet","person",**args)defhello(name:str,age:int):print(f"Hello{name}({age})!")$ python cli.py hello --name Alex --age 35
$ python cli.py hey --name Alex --age 35
$ python cli.py greet person --name Alex --age 35Error handlingOne common problem when adding CLIs to a code base is error handling. When called in a CLI context, you typically want to pretty-print any errors and avoid long tracebacks. However, you don't want to use those errors and plainSystemExits with no traceback in helper functions that are used in other places, or when the CLI functions are called directly from Python or during testing.To solve this,radiclilets you provide an error map via theerrorsargument on initialization. It mapsExceptiontypes likeValueErroror fully custom error subclasses to handler functions. If an error of that type is raised, the handler is called and will receive the error. The handler can optionally return an exit code – in this case,radicliwill perform asys.exitusing that code. If no error code is returned, no exit is performed and the handler can either take care of the exiting itself or choose to not exit.fromradicliimportRadiclifromtermcolorimportcoloreddefpretty_print_error(error:Exception)->int:print(colored(f"🚨{error}","red"))return1cli=Radicli(errors={ValueError:handle_error})@cli.command("hello",name=Arg("--name"))defhello(name:str):ifname=="Alex":raiseValueError("Invalid name")$ python cli.py hello --name Alex
🚨 Invalid name>>>hello("Alex")Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>
ValueError:InvalidnameThis approach is especially powerful with custom error subclasses. Here you can decide which arguments the error should take and how this information should be displayed on the CLI vs. in a regular non-CLI context.classCustomError(Exception):def__init__(self,text:str,additional_info:Any="")->None:self.text=textself.additional_infoself.message=f"{self.text}{self.additional_info}"super().__init__(self.message)defhandle_custom_error(error:CustomError)->int:print(colored(error.text,"red"))print(error.additional_info)return1Using static data for faster help and errorsCLIs often require various other Python packages that need to be imported – for example, you might need to importpytorchandtensorflow, or load other resources in the global scope. This all adds to the CLI's load time, so even showing the--helpmessage may take several seconds to run. That's all unnecessary and makes for a frustrating developer experience.radiclilets you generate a static representation of your CLI as a JSON file, including everything needed to output help messages and to check that the command exists and the correct and required arguments are provided. If the static CLI doesn't perform a system exit via printing the help message or raising an error, you can import and run the "live" CLI to continue. This lets youdefer the import until it's really needed, i.e. to convert the arguments to the expected types and executing the command function.cli.to_static("./static.json")fromradicliimportStaticRadiclistatic=StaticRadicli.load("./static.json")if__name__=="__main__":static.run()# This only runs if the static CLI doesn't error or print helpfrom.cliimportclicli.run()If the CLI is part of a Python package, you can generate the static JSON file during your build process and ship the pre-generated JSON file with your package.StaticRadiclialso provides adisableargument to disable static parsing during development (or if a certain environment variable is set). Settingdebug=Truewill print an additional start and optional end marker (if the static CLI didn't exit before) to indicate that the static CLI ran.Auto-documenting the CLITheRadicli.documentmethod lets you generate a simple Markdown-formatted documentation for your CLI with an optionaltitleanddescriptionadded to the top. You can also include this call in your CI or build process to ensure the documentation is always up to date.withPath("README.md").open("w",encoding="utf8")asf:f.write(cli.document())Thepath_rootlets you provide a customPaththat's used as the relative root for all paths specified as default arguments. This means that absolute paths won't make it into your README.🎛 APIdataclassArgDataclass for describing argument meta information. This is typically used in the command decorators and only includes information for how the argument should be handled on the CLI. Argument types and defaults are read from the Python function.ArgumentTypeDescriptionoptionOptional[str]Option to use on the CLI, e.g.--arg. If unset, argument will be treated as positional.shortOptional[str]Shorthand for option, e.g.-A.helpOptional[str]Help text for argument, used for--help.countboolOnly count and return number of times an argument is used, e.g.--verboseor-vvv(for shorthand-v).converterOptional[Callable[[str], Any]]Converter function that takes the string from the CLI value and returns a value passed to the function.dataclassCommandInternal representation of a CLI command. Can be accessed viaRadicli.commandsandRadicli.subcommands.NameTypeDescriptionnamestrThe name of the command.funcCallableThe decorated command function.argsList[ArgparseArg]The internal representation of the argument annotations.Argparse.arglets you access the originalArg.descriptionOptional[str]The command description, taken from the function docstring.allow_extraboolWhether to allow extra arguments.parentOptional[str]Name of the parent command if command is a subcommand.is_placeholderboolWhether the command is a placeholder, created byRadicli.placeholder. Checking this can sometimes be useful, e.g. for testing. Defaults toFalse.display_namestrThe display name including the parent if available, e.g.parent child.classmethodCommand.from_functionCreate a command from a function and its argument annotations and use the type hints and defaults defined in the function to generate the arguments. This is what happens under the hood in the command decorators and it can be used if you need to construct aCommandmanually.defhello(name:str,age:int):print(f"Hello{name}({age})!")args={"name":Arg(),"age":Arg("--age",help="Your age")}command=Command.from_function("hello",args,hello)ArgumentTypeDescriptionnamestrThe name of the command.argsDict[str, Arg]The command argument annotation, defined asArgdataclasses.funcCallableThe command function.parentOptional[str]Name of the parent command if command is a subcommand.allow_extraboolWhether to allow extra arguments.extra_keystrName of function argument that receives extra arguments ifallow_extraisTrue. Defaults to"_extra".convertersDict[Type, Callable[[str], Any]]Dict mapping types to global converter functions.RETURNSCommandThe command.classRadicliAttributesNameTypeDescriptionprogOptional[str]Program name displayed in--helpprompt usage examples, e.g."python -m spacy".helpstrHelp text for the CLI, displayed in top-level--help. Defaults to"".versionOptional[str]Version available via--version, if set.convertersDict[Type, Callable[[str], Any]]Dict mapping types to global converter functions.errorsDict[Type[Exception], Callable[[Exception], Optional[int]]]Dict mapping errors types to global error handlers. If the handler returns an exit code, asys.exitwill be raised using that code. Seeerror handlingfor details.commandsDict[str, Command]The commands added to the CLI, keyed by name.subcommandsDict[str, Dict[str, Command]]The subcommands added to the CLI, keyed by parent name, then keyed by subcommand name.methodRadicli.__init__Initialize the CLI and create the registry.fromradicliimportRadiclicli=Radicli(prog="python -m spacy")ArgumentTypeDescriptionprogOptional[str]Program name displayed in--helpprompt usage examples, e.g."python -m spacy".helpstrHelp text for the CLI, displayed in top-level--help. Defaults to"".versionOptional[str]Version available via--version, if set.convertersDict[Type, Callable[[str], Any]]Dict mapping types to converter functions. All arguments with these types will then be passed to the respective converter.errorsDict[Type[Exception], Callable[[Exception], Optional[int]]]Dict mapping errors types to global error handlers. If the handler returns an exit code, asys.exitwill be raised using that code. Seeerror handlingfor details.extra_keystrName of function argument that receives extra arguments if thecommand_with_extraorsubcommand_with_extradecorator is used. Defaults to"_extra".decoratorRadicli.command,Radicli.command_with_extraThe decorator used to wrap top-level command functions.@cli.command("hello",name=Arg(help="Your name"),age=Arg("--age","-a",help="Your age"),greet=Arg("--greet","-G",help="Whether to greet"),)defhello(name:str,age:int,greet:bool=False)->None:ifgreet:print(f"Hello{name}({age})")$ python cli.py hello Alex --age 35 --greet
Hello Alex (35)@cli.command_with_extra("hello",name=Arg(help="Your name"),age=Arg("--age","-A",help="Your age"),)defhello(name:str,age:int,_extra:List[str])->None:print(f"Hello{name}({age})",_extra)$ python cli.py hello Alex --age 35 --color red
Hello Alex (35) ['--color', 'red']ArgumentTypeDescriptionnamestrName of the command.**argsArgKeyword arguments defining the argument information. Names need to match the function arguments. If no argument annotations are defined, all arguments are treated as positional.RETURNSCallableThe wrapped function.decoratorRadicli.subcommand,Radicli.subcommand_with_extraThe decorator used to wrap one level of subcommand functions.@cli.subcommand("hello","world",name=Arg(help="Your name"))defhello_world(name:str)->None:print(f"Hello world,{name}!")$ python cli.py hello world Alex
Hello world, Alex!@cli.subcommand_with_extra("hello","world",name=Arg(help="Your name"))defhello_world(name:str,_extra:List[str])->None:print(f"Hello world,{name}!",_extra)$ python cli.py hello world Alex --color blue
Hello world, Alex! ['--color', 'blue']ArgumentTypeDescriptionparentstrName of the parent command (doesn't need to exist).namestrName of the subcommand.**argsArgKeyword arguments defining the argument information. Names need to match the function arguments.RETURNSCallableThe wrapped function.methodRadicli.placeholderAdd empty parent command with custom description text for subcommands without
an executable parent.cli.placeholder("parent",description="This is the top-level command description")@cli.subcommand("parent","child",name=Arg("--name",help="Your name"))defchild(name:str)->None:print(f"Hello{name}!")ArgumentTypeDescriptionnamestrName of the command.descriptionOptional[str]Command description for help texts.methodRadicli.runRun the CLI. Typically called in aif __name__ == "__main__":block at the end of a file or in a package's__main__.pyto allow executing the CLI viapython -m [package].if__name__=="__main__":cli.run()ArgumentTypeDescriptionargsOptional[List[str]]Optional command to pass in. Will be read fromsys.argvif not set (standard use case).methodRadicli.callCall a command with args.command=cli.commands["hello"]cli.call(command,["Alex","--age","35"])ArgumentTypeDescriptioncommandCommandThe command.argsOptional[List[str]]Optional command to pass in. Will be read fromsys.argvif not set (standard use case).methodRadicli.parseParse a list of arguments for a given command. Typically internals, but can also be used for testing.command=cli.commands["hello"]values=cli.parse(["Alex","--age","35"],command)command.func(**values)ArgumentTypeDescriptionargsList[str]The string arguments, e.g. what's received from the command line.commandCommandThe command.subcommandsDict[str, Command]Subcommands of the parent command, if available, keyed by subcommand name. Defaults to{}.allow_partialboolAllow partial parsing and still return the parsed values, even if required arguments are missing. Defaults toFalse.RETURNSDict[str, Any]The parsed values keyed by argument name that can be passed to the command function.methodRadicli.documentGenerate a Markdown-formatted documentation for a CLI.withPath("README.md").open("w",encodig="utf8")asf:f.write(cli.document())ArgumentTypeDescriptiontitleOptional[str]Title to add to the top of the file. Defaults toNone.descriptionOptional[str]Description to add to the top of th file. Defaults toNone.commentOptional[str]Text of the HTML comment added to the top of the file, usually indicating that it's auto-generated. IfNone, no comment will be added. Defaults to"This file is auto-generated".path_rootOptional[Path]Custom path used as relative root for argument defaults of typePath, to prevent local absolute paths from ending up in the documentation. Defaults toNone.RETURNSstrThe Markdown-formatted docs.methodRadicli.to_staticExport a static JSON representation of the CLI forStaticRadicli.cli.to_static("./static.json")ArgumentTypeDescriptionfile_pathUnion[str, Path]The path to the JSON file.RETURNSPathThe path the data was saved to.methodRadicli.to_static_jsonGenerate a static representation of the CLI forStaticRadiclias a JSON-serializable dict.data=cli.to_static_json()ArgumentTypeDescriptionRETURNSDict[str, Any]The static data.classStaticRadicliSubclass ofRadicliand static version of the CLI that can be loaded from a static representation of the CLI, generated withRadicli.to_static. The static CLI can run before importing and running the live CLI and will take care of showing help messages and doing basic argument checks, e.g. to ensure all arguments are correct and present. This can make your CLI help significantly faster by deferring the import of the live CLI until it's really needed, i.e. to convert the values and execute the function.static=StaticRadicli.load("./static.json")if__name__=="__main__":static.run()# This only runs if the static CLI doesn't error or print helpfrom.cliimportclicli.run()classmethodStaticRadicli.loadLoad the static CLI from a JSON file generated withRadicli.to_static.static=StaticRadicli.load("./static.json")ArgumentTypeDescriptionfile_pathUnion[str, Path]The JSON file to load.disableboolWhether to disable static parsing. Can be useful during development. Defaults toFalse.debugboolEnable debugging mode and print an additional start and optional end marker (if the static CLI didn't exit before) to indicate that the static CLI ran. Defaults toFalse.convertersDict[Type, Callable[[str], Any]]Dict mapping types to global converter functions that will be used to deserialize types.methodStaticRadicli.__init__Initialize the static CLI with the JSON-serializable static representation.data=cli.to_static_json()static=StaticRadicli(data)ArgumentTypeDescriptiondataDict[str, Any]The static data.disableboolWhether to disable static parsing. Can be useful during development. Defaults toFalse.debugboolEnable debugging mode and print an additional start and optional end marker (if the static CLI didn't exit before) to indicate that the static CLI ran. Defaults toFalse.convertersDict[Type, Callable[[str], Any]]Dict mapping types to global converter functions that will be used to deserialize types.methodStaticRadicli.runRun the static CLI. Typically called before running the live CLI and will perform a system exit if a help message was printed (0) or if argument names were missing or incorrect (1). This means you can defer loading the live CLI until it's really needed, , i.e. to convert the values and execute the function.if__name__=="__main__":static.run()from.cliimportclicli.run()ArgumentTypeDescriptionargsOptional[List[str]]Optional command to pass in. Will be read fromsys.argvif not set (standard use case).Custom types and convertersThe package includes several converters enabled by default, as well as custom types implemented asNewTypes with pre-defined converter functions. If these types are used in the decorated function, the values received from the CLI will be converted and validated accordingly.NameTypeDescriptionExistingPathPathReturns a path and checks that it exists.ExistingFilePathPathReturns a path and checks that it exists and is a file.ExistingDirPathPathReturns a path and checks that it exists and is a directory.ExistingPathOrDashUnion[Path, Literal["-"]]Returns an existing path but also accepts"-"(typically used to indicate that a function should read from standard input).ExistingFilePathOrDashUnion[Path, Literal["-"]]Returns an existing file path but also accepts"-"(typically used to indicate that a function should read from standard input).ExistingDirPathOrDashUnion[Path, Literal["-"]]Returns an existing directory path but also accepts"-"(typically used to indicate that a function should read from standard input).PathOrDashUnion[Path, Literal["-"]]Returns a path but also accepts"-"(typically used to indicate that a function should read from standard input).UUIDUUIDConverts a value to a UUID.StrOrUUIDUnion[str, UUID]Converts a value to a UUID if valid, otherwise returns the string.get_list_converterHelper function that creates a list converter that takes a string of list items separated by a delimiter and returns a list of items of a given type. This can be useful if you prefer lists to be defined as comma-separated strings on the CLI instead of via repeated arguments.@cli.command("hello",items=Arg("--items",converter=get_list_converter(str)))defhello(items:List[str])->None:print(items)ArgumentTypeDescriptiontype_funcCallable[[Any], Union[bool, int, float]]The function to convert the list items. Can be a builtin likestrorint, or a custom converter function.delimiterstrDelimiter of the string. Defaults to",".RETURNSCallable[[str], List]Converter function that converts a string to a list of the given type.