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?
Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
This is the way to go. Use an existing parser to parse your string and then have it fill in the variables within a function object. If it's a complete function, then you'll have to get a more powerful parser. Bingo, like PIL's 'tostring' and 'fromstring' methods, liking yamls object creation as well it seems fun.
To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.
This does not exactly answer your question, but maybe it helps nevertheless:
As mentioned, eval
should be avoided if possible. A better way imo is to use dictionary unpacking. This is also very dynamic and less error prone.
Example:
def fullName(name = "noName", family = "noFamily"): return name + family functionList = {'fullName': fullName} function = 'fullName' parameters = {'name': 'Foo', 'family': 'Bar'} print functionList[function](**parameters) # prints FooBar parameters = {'name': 'Foo'} print functionList[function](**parameters) # prints FoonoFamily
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With