I made a switch class. It is initialized with the value, a dict where the key, value pairs represent the actions for each value as a list containing a function and optional parameters and an optional default action.
For example you should call it like this:
sw = switch(some_value,
{
1:[print, 'hello'],
2:[print, 'goodby']
},
default=[print])
Tthe default argument has no parameters, so just print a new line.
The corresponding function is called when the switch is called:
sw()
The good thing is that as a switch
object has a __call__
method, switches can be nested.
Here is the implementation and the application for your case:
class switch(dict):
def __init__(self, value, cases, default = ((lambda:None),)):
super().__init__(cases)
self.default = default
self.value = value
def __call__(self):
do = self.get(self.value, self.default)
return do[0](*do[1:])
sw = switch(where_clause,
{
0: [requete],
1: [switch(like_clause,
{
0: [switch(any_clause,
{
1: [requete_where_any,liste_fields,schema,table, wc_1, any_1]
},
default=[requete_where,liste_fields,schema,table, wc_1, wc_2])],
1: [requete_like,liste_fields,schema,table, like_1, like_2]
},
default=[requete_like,liste_fields,schema,table, like_1, like_2])],
2: [requete_double_where,liste_fields,schema,table, wc_1, wc_2, wc_3, wc_4),
3: [requete_triple_or,liste_fields,schema,table, oc_1, oc_2, oc_3, oc_4]
})
sw()
The class could be easily improved having the option to not pass a value at initialization, and to pass a value at call time, so for example:
sw = switch(
{
1:[print, 'hello'],
2:[print, 'goodby']
})
sw(1) # -> 'hello'
sw(2) # -> 'goodby'