5

I'm trying to use inspect.getmembers to check for classes and functions inside a file. The problem is that I don't know how to pass the name of the file to inspect.getmembers without using import. That's because I need to specify a different file name each time

The code looks similar to this:

def extractName(self,fileName):

    for name, obj in inspect.getmembers(FileName):
        if inspect.isclass(obj):

            print "this is class",name


    if inspect.isfunction(obj):

        print "this is method",name
Garrett Hyde
  • 5,409
  • 8
  • 49
  • 55
tkyass
  • 2,968
  • 8
  • 38
  • 57
  • it sounds like you'd like to import a module based on it's name? – Thomas Oct 21 '12 at 02:21
  • 2
    See the answer of http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path on how to get the module object of a python source file given its path. – Dan D. Oct 21 '12 at 02:21
  • Is the second `if` statement suppose to be inside of your `for` loop? – Garrett Hyde Oct 22 '12 at 00:13

1 Answers1

6

In order to inspect a module, you must execute it somehow; otherwise, the definitions in the file won't be available.

You can use module = __import__(modname) to import a module by name, or module = imp.load_source("__inspected__", path) to import a module by path.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • thanks for the answer , but the problem is that I want to let any one who run the program to specify file name that could be different each time.. so is there any way to do so?? – tkyass Oct 21 '12 at 02:25
  • That only works if you have the module's name, as in this case we don't. Instead with pathname which we have use: `imp.load_source("the value of this string doesn't matter", '/path/to/file.py')` from http://stackoverflow.com/a/67692 – Dan D. Oct 21 '12 at 02:32
  • Thanks, added `imp.load_source`. – nneonneo Oct 21 '12 at 02:35