Commit 5697793b86539c29ce56642a2250a38456d96f00

Authored by Quillot Mathias
1 parent ff117f2ef0
Exists in master

New utility class to help creating sub command runners using argparse.

Showing 1 changed file with 76 additions and 0 deletions Inline Diff

File was created 1
2 class SubCommandRunner:
3 """This class provides a simple way to call subcommands
4 from argparsers ones. Soon, we will add some examples to
5 into the documentation.
6 """
7
8 def __init__(self, choice_dict):
9 """Initialisation of choices
10
11 Args:
12 choice_dict (dict): A dictionary where each string key is associated
13 to a function to call.
14 """
15 self._choice_dict = choice_dict
16
17 def run(self, choice, args=None, remove=[]):
18 """Run a function as the choice key.
19
20 Args:
21 choice (str): [description]
22 args (dict, optional): dictionnary of arguments. Defaults to None.
23 remove (list, optional): list of key to remove from arguments. Defaults to [].
24 """
25 if args is not None:
26 copy_dict = args.copy()
27 if type(remove) == list:
28 [copy_dict.pop(v) for v in remove]
29 else:
30 copy_dict.pop(remove)
31
32 try:
33 if args is None:
34 self._choice_dict.get(choice)()
35 else:
36 self._choice_dict.get(choice)(**copy_dict)
37 except TypeError as e:
38 print("TYPE ERROR HANDLED")
39 print("Value of args: ", args)
40 raise(e)
41
42 if __name__ == "__main__":
43 ''' Just a dumb function '''
44 def dumb1():
45 print("Dumb 1")
46
47 ''' Just a dumb function with one parameter '''
48 def dumb2(param1):
49 print("Dumb 2: ", param1)
50
51 print("Utils run mode is just used to test implementation of class and function implementation.")
52
53 runner = SubCommandRunner({
54 "dumb1": dumb1,
55 "dumb2": dumb2
56 })
57
58 dumb2_args = {
59 "param1": "Le paramètre 1"
60 }
61
62 dumb2_args_which = {
63 "param1": "Le paramètre 1 une seconde fois",
64 "which": "which value usally defined and need to be removed"
65 }
66
67 dumb2_args_which_array = {
68 "param1": "Le paramètre 1 une troisième fois",
69 "which": "which value usally defined and need to be removed",
70 "param2": "Imagine you want to remove multiple values"
71 }
72
73 runner.run("dumb1", None)
74 runner.run("dumb2", dumb2_args)
75 runner.run("dumb2", dumb2_args_which, remove="which")
76 runner.run("dumb2", dumb2_args_which_array, remove=["which", "param2"])