Home > Mobile >  Need to pass the whole function code as argument
Need to pass the whole function code as argument

Time:06-22

I have a special requirement where I am storing the python function code in a Table and fetching the same to be passed as argument and somehow call it and execute it.

For testing the same, I am trying to just check with a print statement if I can achieve the requirement. So here is how the code looks like.

rule_name, rule_string = fetch_rule_table('Rule_Table')
def func1(func):
    # storing the function in a variable
    res = func("Hello World")
    print(res)

rule_string

func1(rule_name)

Now the variable rule_name has the value bar and variable rule_string fetches the string which consists of the python function code, itself, which looks like below:-

def bar():
    print("In bar().")

As the rule_string is just a string object, it cannot be call itself as the function, hence can somebody help here to get this working. the requirement is to save the rule function code in table and once fetched from table, we need to execute them as it is to get the required value.

CodePudding user response:

You probably don't want to store the code of the function in a variable, but rather the function itself. Here's a working example that follows the rough outline of what your code is trying to do:

def bar(msg):
    return f"In bar(): '{msg}'!"

def fetch_rule_table():
    return "bar", bar

rule_name, rule_func = fetch_rule_table()

def func1(func):
    print(func("Hello World"))

func1(rule_func)
# In bar(): 'Hello World'!

CodePudding user response:

You may want to take a look at this. It seems to answer your question. The eval() function may let you work as you want to, but as far as I know you will still have to declare the functions in your table for them to work when the string gets parsed. This other article explains the function a little bit further.

Another way could be to map the strings to functions in a dictionary.

  • Related