Stat-R
Stat-R

Reputation: 5270

Create a function that takes a module as string and displays all functions in it

I am on Windows 7 (x64) using python 2.7.13 (x64). I am trying to create a function to display functions in a module. Here is what I tried.

from __future__ import division, absolute_import, print_function
# from sys import argv
# import sys
import importlib

def see(module_here):
    print("Functions in " + module_here + " module")
    importlib.import_module(module_here)
    a1 = dir(module_here)
    for i,v in enumerate(a1):
        print(str(i) + ") " + v)
see('sys')      

I am not getting the desired result of "printing functions in sys module'. Instead it is printing functions associated with the string 'sys'. The result would have been the same if I were to use see('this_does_not_exist').

I would be grateful if some python user/expert help me correct the code.

Upvotes: 2

Views: 55

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

That's because you call:

importlib.import_module(module_here)

but don't do anything with the result. The correct code should be:

from __future__ import division, absolute_import, print_function
# from sys import argv
# import sys
import importlib

def see(module_here):
    print("Functions in " + module_here + " module")
    result = importlib.import_module(module_here)
    a1 = dir(result)
    for i,v in enumerate(a1):
        print(str(i) + ") " + v)
see('sys')

Mind however that this will print all elements in sys, not only the functions. You will need to do additional filtering to print only functions.

You could use - as @Vincenzzzochi says - the inspect.is_function to check if it is a function:

from __future__ import division, absolute_import, print_function
# from sys import argv
# import sys
import importlib
import inspect

def see(module_here):
    print("Functions in " + module_here + " module")
    result = importlib.import_module(module_here)
    a1 = dir(result)
    for i,v in enumerate(f for f in a1 if inspect.isfunction(f)):
        print(str(i) + ") " + v)
see('sys')

Upvotes: 4

Related Questions