Altamash Rafiq
Altamash Rafiq

Reputation: 349

How can I convert a string to a function in Python?

I have a function that I have as a string as follows :-

"def tree(inp):\n\tif inp = 'hello':\n\t\tprint('hello')\n\telse:\n\t\tprint('fake news')"

I want this function to save properly as a function as follows:

def tree(inp):
    if inp == 'hello':
        print('hello')
    else:
        print('fake news')

How can I take this string and save it as a function like this without constant copy pasting?

Upvotes: 1

Views: 73

Answers (2)

Md. Mehedi Hasan Khan
Md. Mehedi Hasan Khan

Reputation: 51

This can be it :

def tree(inp):
    if inp = 'hello':
        print('hello')
    else:
        print('fake news')

Upvotes: 0

chepner
chepner

Reputation: 532418

Your string itself contains the syntax error; you use = where you should have used ==.

Having fixed that, you can use exec:

>>> fstr = "def tree(inp):\n\tif inp == 'hello':\n\t\tprint('hello')\n\telse:\n\t\tprint('fake news')"
>>> exec(fstr)
>>> tree("hello")
hello
>>> tree("bye")
fake news

Upvotes: 1

Related Questions