I have a list of numbers and I want to, for (for example) the first term and the second term, perform every function in my imported math
module.
import math
list = [1, 2, 3]
#do stuff that will print (for example) 2+1, 2-1, 2/1, etc.
I have a list of numbers and I want to, for (for example) the first term and the second term, perform every function in my imported math
module.
import math
list = [1, 2, 3]
#do stuff that will print (for example) 2+1, 2-1, 2/1, etc.
Here's a simple method. You'll need to specify what happens if the function doesn't expect two arguments.
for name in dir(math):
item = getattr(math, name)
if callable(item):
item(list[0], list[1])
If you have your own math module, don't name it "math" as Python already has a standard math module. Name it something more unique to avoid confusion and possible conflicts with the Python math module.
Second, to get a list of functions from within a module take a look at the Python "inspect" module -> https://docs.python.org/2/library/inspect.html#inspect.getmembers
import inspect
import myMathModule
for name, member in inspect.getmembers(myMathModule):
print name, 'is function', inspect.isfunction(member)
You can also inspect function arguments to make sure they accept say, two arguments or filter out ones from your list. But I don't think this is a good idea to use in production code. Maybe to test if you are certain it will work, otherwise I would use a list of function names that you will pull rather than any function in a module.
Based on the answer of @Alex Hall, I want to add an exception handling to avoid having passed two parameters to a function which takes one argument. Here is the changed code:
for name in dir(math):
item = getattr(math, name)
if callable(item):
try:
item(list[0], list[1])
# The function does not take two arguments or there is any other problem.
except TypeError:
print(item, "does not take two arguments.")