Just use the functions themselves:
from math import sin, cos, tan
li = [sin, cos, tan]
If you really need to use strings, create a dict:
funcs = {'sin': sin, 'cos': cos, 'tan': tan}
func = funcs[string]
func(x)
Domanda
In Python I am trying to figure out how to evaluate commands given as strings in a program. For example, consider the built in math functions sin
, cos
and tan
Say I am given these functions as a list;
li = ['sin', 'cos', 'tan']
Now, I want to iterate over each element in the list and apply each function to a numeric argument:
x = 45
for func in li:
func(x)
The above clearly will not work as func is a string and just shows the idea. In lisp I could make each function a quoted symbol and then evaluate similarly to the above (well in lisp syntax of course, but the idea is the same).
How is this done in python?
Thanks and let me know if you need more information!
Soluzione
Just use the functions themselves:
from math import sin, cos, tan
li = [sin, cos, tan]
If you really need to use strings, create a dict:
funcs = {'sin': sin, 'cos': cos, 'tan': tan}
func = funcs[string]
func(x)
Altri suggerimenti
There are a several options here, I've listed some of the better options below:
If all of the functions come from the same module, you can use module.getattr(func)
to access the function. In this case sin, cos, and tan are all functions from math so you could do the following:
import math
li = ['sin', 'cos', 'tan']
x = 45
for func in li:
x = getattr(math, func)(x)
Create a dictionary mapping names to functions, and use that as a lookup table:
import math
table = {'sin': math.sin, 'cos': math.cos, 'tan': math.tan}
li = ['sin', 'cos', 'tan']
x = 45
for func in li:
x = table[func](x)
Put the functions in your list directly:
import math
li = [math.sin, math.cos, math.tan]
x = 45
for func in li:
x = func(x)
Assuming you're getting these strings from something like user input, so you can't just change your input to be a list of functions, you have several ways to do this. One way would be to look up the functions in the math
module:
import math
name = 'sin'
getattr(math, name) # Gives the sin function
Alternatively, you can build a dict mapping names to functions:
funcs = {'sin': math.sin, 'cos': math.cos, 'tan': math.tan}
funcs['sin'] # Gives the sin function
If these are functions of a module (the ones of the example are functions of math
module) you can use getattr
:
import math
li = ['sin', 'cos', 'tan']
x = 45
for func in li:
f = getattr(math, func)
f(x)
If you don't need to be strings you can make a list of functions:
import math
li = [sin, cos, tan]
x = 45
for func in li:
func(x)