From 5697793b86539c29ce56642a2250a38456d96f00 Mon Sep 17 00:00:00 2001 From: Quillot Mathias Date: Fri, 23 Apr 2021 17:16:30 +0200 Subject: [PATCH] New utility class to help creating sub command runners using argparse. --- volia/utils.py | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 volia/utils.py diff --git a/volia/utils.py b/volia/utils.py new file mode 100644 index 0000000..9f6edea --- /dev/null +++ b/volia/utils.py @@ -0,0 +1,76 @@ + +class SubCommandRunner: + """This class provides a simple way to call subcommands + from argparsers ones. Soon, we will add some examples to + into the documentation. + """ + + def __init__(self, choice_dict): + """Initialisation of choices + + Args: + choice_dict (dict): A dictionary where each string key is associated + to a function to call. + """ + self._choice_dict = choice_dict + + def run(self, choice, args=None, remove=[]): + """Run a function as the choice key. + + Args: + choice (str): [description] + args (dict, optional): dictionnary of arguments. Defaults to None. + remove (list, optional): list of key to remove from arguments. Defaults to []. + """ + if args is not None: + copy_dict = args.copy() + if type(remove) == list: + [copy_dict.pop(v) for v in remove] + else: + copy_dict.pop(remove) + + try: + if args is None: + self._choice_dict.get(choice)() + else: + self._choice_dict.get(choice)(**copy_dict) + except TypeError as e: + print("TYPE ERROR HANDLED") + print("Value of args: ", args) + raise(e) + +if __name__ == "__main__": + ''' Just a dumb function ''' + def dumb1(): + print("Dumb 1") + + ''' Just a dumb function with one parameter ''' + def dumb2(param1): + print("Dumb 2: ", param1) + + print("Utils run mode is just used to test implementation of class and function implementation.") + + runner = SubCommandRunner({ + "dumb1": dumb1, + "dumb2": dumb2 + }) + + dumb2_args = { + "param1": "Le paramètre 1" + } + + dumb2_args_which = { + "param1": "Le paramètre 1 une seconde fois", + "which": "which value usally defined and need to be removed" + } + + dumb2_args_which_array = { + "param1": "Le paramètre 1 une troisième fois", + "which": "which value usally defined and need to be removed", + "param2": "Imagine you want to remove multiple values" + } + + runner.run("dumb1", None) + runner.run("dumb2", dumb2_args) + runner.run("dumb2", dumb2_args_which, remove="which") + runner.run("dumb2", dumb2_args_which_array, remove=["which", "param2"]) \ No newline at end of file -- 1.8.2.3