-1

I'm trying to automate the resolution of tickets. Indeed, my idea is to parse an input with the format: server_name | alert, and depending of what the server_name and the alert are, execute an action (= function). My first idea was to resolve this with an if/elif block code but starting to code it seemed to me inefficient and long.

if server_name == 'Z':
    if alert == 'a':
        action1()
    elif alert == 'b':
        action2()
        ...
elif server_name == 'Y':
    if alert == 'a':
        action3()
    elif alert == 'b':
        action4()
        ...
...

I did research and creating a grammar seems like a better solution, maybe with re module, ast module or dis module. But the grammars I saw always include math, I just need to evaluate strings. Does anyone know what is best for this situation or do you know if there is a better solution? Thank you.

Raphael
  • 57
  • 6
  • 2
    Make a dictionary, instead of nested if/elif/else blocks – buran Mar 12 '21 at 10:09
  • Something like: dict = {"server_name1": "alert1", "server_name2": "alert2"...} and create an if/elif code block to evaluate the key:value to execute the action? – Raphael Mar 12 '21 at 10:14

1 Answers1

1

Something like this with tuples as keys:

actions = {('Z', 'a'):action1,
           ('Z', 'b'):action2,
           ('Y', 'a'):action3,
           ('Y', 'b'):action4}
server = 'Y'
alert = 'a'
actions[(server, alert)]() # execute it

you can go fancy with named tuple, etc.

or

nested dict

actions = {'Z':{'a':action1,
                'b':action2},
           'Y':{'a':action3,
                'b':action4}}
server = 'Y'
alert = 'a'
actions[server][alert]() # execute it

In both cases I assume you have functions for actions defined as well.

Note, in 3.10 (now in dev) we will get structural pattern matching.

buran
  • 13,682
  • 10
  • 36
  • 61
  • Thanks for the reply ! I probably will do something like that, but don't you think it could be a better solution with a grammar done with ast module? – Raphael Mar 12 '21 at 10:39
  • 1
    No, this is idiomatic way to do it (see https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) at least for now, until 3.10 is released when we get [structural pattern matching](https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching) – buran Mar 12 '21 at 11:04