1

I'm writing a python function that calls a function based on a parameter it takes. It looks something like this:

def match(parameter):
  if parameter == 'fun1':
    fun1()
  elif parameter == 'fun2':
    fun2()
  elif parameter == 'fun3':
    fun3()

All those functions being called are then defined below the match function. Is there a more efficient way to organize the match function? I can't find anything about pattern matching with functions, but could a data structure of some sort work?

Thanks for the help.

1 Answer 1

2

You can create a dictionary which stores the mapping between the function and the parameter value to call it.

For example:

def fun1():
    print("I am fun1")


def fun2():
    print("I am fun2")

funcs_mapping = {"fun1":fun1, "fun2":fun2}

def match(parameter):
  if parameter in funcs_mapping:
      funcs_mapping[parameter]()

Sign up to request clarification or add additional context in comments.

7 Comments

different functions may have different arguments
How do you know that @abhinonymous
@abhinonymous Then you can wrap each function in a lambda or a partial before storing it in the dictionary (wait, you're not the OP).
@abhinonymous According to OP's question, the functions don't receive any params.
One difference between this code and OPs is how it handles unknown keys. The OP just returns None, this will raise an exception.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.