1

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.
mkpappu
  • 358
  • 1
  • 3
  • 16
  • Possible duplicate of [How to iterate through a module's functions](http://stackoverflow.com/questions/21885814/how-to-iterate-through-a-modules-functions) – James Apr 16 '16 at 23:16

3 Answers3

1

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])
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

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.

scottiedoo
  • 309
  • 2
  • 10
  • I'm importing Python's math module. I know I can list all the functions by using the inspect module, but I wanted to then perform those functions and I was wondering if there was a specific piece of code that would allow me to do so. – mkpappu Apr 16 '16 at 23:24
  • You can just call it like my example, but you may want to test what arguments the function needs first before calling or wrap it with try, except. member(1,2) – scottiedoo Apr 16 '16 at 23:29
  • Sorry about not understanding that you are referring to Python math module, not "my imported math module" – scottiedoo Apr 16 '16 at 23:40
0

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.")
ismailarilik
  • 2,236
  • 2
  • 26
  • 37