0

Imports a module and then goes through the module's namespace to find any functions (you may assume any object with a call() method is a function) and print the names of the functions and their arguments, in the same way as it might appear in a def statement.

My problem is after I have loop through the module and gotten all the function I can not pass the function name to inspect.getfullargspec() because it is a string.How do i make the string callable?

import inspect
from smtplib import SMTP
from pprint import pprint
def func(x):     
    for item in inspect.getmembers(x):
         lst = inspect.getmembers(x, inspect.isfunction)
         for items in lst:
              func_names = items[0] #names of functions               
              f = r"%s.%s" % (x.__name__, func_names)
              arg = inspect.getargspec(f)
              print(f)



if __name__ == '__main__':
     func(SMTP)
Python_Woo
  • 21
  • 1
  • 2
  • 5

2 Answers2

2

You've got a few mistakes in this. The quick answer, though, is that that you don't want to make string callable, you just need to know that inspect.getmembers returns a list of ('func_name', <function object>) pairs, and inspect.getargspec expects a function object.

So you could make your for-loop look like this:

for name, fun in lst:
    long_name = r"%s.%s" % (x.__name__, name)
    argspec = inspect.getargspec(fun)
    print(long_name)

As a separate issue, you rvariable names are mostly nondescriptive and occasionally incorrect. For example, what you call func_names is always exactly one name, and the variable lst would be more usefully named members, and item should be member. Naming a function func is not normally good practice, especially when that function needs several variables inside of that should also, more appropriately, be named func.

quodlibetor
  • 8,185
  • 4
  • 35
  • 48
0

lst here is a tuple of function name and function object, you do not really need to do all the string manipulation. Below simple method will do the job:

def func(module):
    for lst in inspect.getmembers(module, inspect.isfunction):
        if inspect.isfunction(lst[1]):# Doing an additional check, may not be actually required
            print(lst[0]+inspect.formatargspec(*inspect.getfullargspec(lst[1])))
Mohsin
  • 221
  • 2
  • 7