Konstantin
Konstantin

Reputation: 3159

Get all class names in a Python package

I need to get the list of all classes in Python package. At first I get all filenames (it works fine, took it from stackoverflow):

from os import listdir, getcwd
from os.path import isfile, join
mypath = getcwd()
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

Then I inspect all files and it doesn't work properly:

for x in onlyfiles:
    for name, obj in inspect.getmembers(x):
        if inspect.isclass(obj):
            print obj

The output is:

<type 'str'>
....
<type 'str'>

However, the following code works properly:

    for name, obj in inspect.getmembers(example.py):
        if inspect.isclass(obj):
            print obj

Could you help me to figure out what the mistake is?

Upvotes: 13

Views: 16972

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125058

inspect.getmembers() works on objects, and you are passing in strings. Python doesn't know these strings contain filenames or will treat these filenames as modules to import.

You'd have to import the files for inspect.getmembers() to work. Because you are working with files in the current directory, you should be able to just import them all:

import importlib

for x in onlyfiles:
    module = importlib.import_module(x)
    for name, obj in inspect.getmembers(module):
        if inspect.isclass(obj):
            print obj

Note that inspect.getmembers() accepts a second argument, the predicate that lets you filter what the method returns. Instead of filtering manually, you could just use inspect.isclass() as the predicate here:

for x in onlyfiles:
    module = importlib.import_module(x)
    for name, obj in inspect.getmembers(module, inspect.isclass):
        print obj

Upvotes: 15

anon582847382
anon582847382

Reputation: 20391

Try this, using the inspect module:

import sys
import inspect

clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)

This runs within a live file.

Upvotes: 4

Related Questions