Blame view
volia/utils.py
2.3 KB
5697793b8 New utility class... |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 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"]) |