utils.py 2.29 KB
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": "Parameter 1"
    }
    
    dumb2_args_which = {
        "param1": "Parameter one a second time",
        "which": "which value usally defined and need to be removed"
    }

    dumb2_args_which_array = {
        "param1": "Parameter one a third time",
        "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"])