Use a string to call function in Python

function, python, string

Solution

You could use eval():

myString = "fullName( name = 'Joe', family = 'Brand' )"
result = eval(myString)

Beware though, `eval()` is considered evil by many people.

Problem

Some days ago I was searching on the net and I found an interesting article about python dictionaries. It was about using the keys in the dictionary to call a function. In that article the author has defined some functions, and then a dictionary with key exactly same as the function name. Then he could get an input parameter from user and call the same method (something like implementing case break) After that I realised about the same thing but somehow different. I want to know how I can implement this. If I have a function: ``` def fullName( name = "noName", family = "noFamily" ): return name += family ``` And now if I have a string like this: ``` myString = "fullName( name = 'Joe', family = 'Brand' )" ``` Is there a way to execute this query and get a result: JoeBrand For example something I remember is that we might give a string to exec() statement and it does it for us. But I’m not sure about this special case, and also I do not know the efficient way in Python. And also I will be so grateful to help me how to handle that functions return value, for example in my case how can I print the full name returned by that function?

Original source

Related problems