0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Sanjib Behera
  • 101
  • 1
  • 13

1 Answers1

2

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'!
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • A lot of people don't understand the mechanics of Python. When you do `def foo():` you create an object that contains the actual function and assign it to the variable `foo`. – Mark Ransom Jun 21 '22 at 21:15