Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all class names in a Python package

Tags:

python

class

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?

like image 671
Konstantin Avatar asked Mar 01 '14 20:03

Konstantin


People also ask

How do I get a list of classes in Python?

Using built-in dir() Function To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir(). Example: Python3.

What is __ all __ in Python?

Python __all__ It's a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore.

How do I find out what modules are in a Python package?

Get the location of a particular module in Python using the OS module. For a pure Python module, we can locate its source by module_name. __file__. This will return the location where the module's .

How do you get all the methods in a module?

Method 1: Using the dir() Function: We have first to import the module in the Python shell, and then we have to write the module name in the dir() method, and it will return the list of all functions present in a particular Python module.


1 Answers

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
like image 157
Martijn Pieters Avatar answered Sep 23 '22 04:09

Martijn Pieters