Python: get only classes defined in imported module with dir ()?

I have a module written in Python. Now I want to import it into another script and a list of all the classes defined in this module. Therefore, I try:

>>> import my_module
>>> dir(my_module)
['BooleanField', 'CharField', 'DateTimeField', 'DecimalField', 'MyClass', 'MySecondClass', 'ForeignKeyField', 'HStoreField', 'IntegerField', 'JSONField', 'TextField', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'datetime', 'db', 'division', 'os', 'struct', 'uuid']

The only two classes that I defined in my_module are MyClassand MySecondClass, the rest of the things are all that I imported into my_module.

Now I want to somehow get a list of all the classes that are defined in my_module, without getting anything else. Is there a way to do this in Python?

+4
source share
3 answers

Use the module inspectto check live objects:

>>> import inspect
>>> import my_module
>>> [m[0] for m in inspect.getmembers(my_module, inspect.isclass) if m[1].__module__ == 'my_module']

, class, my_module.

+14

Python Class Browser

import pyclbr
module_name = 'your_module'
module_info = pyclbr.readmodule(module_name)
print(module_info)

for item in module_info.values():
    print(item.name)

, your_module

+3

If you really want to use dir (), here it is:

>>> import module
>>> [eval("module." + objname) for objname in dir(module) if type(eval("module." + objname)) is type]

or (script)

import module
classes = []
for objname in dir(module):
    obj = eval("module." + objname)
    if type(obj) is type:
        classes.append(obj)
print(classes)

But this uses the eval function and is really unsafe to use. I stick to the selected answer

0
source

Source: https://habr.com/ru/post/1532977/


All Articles