James
James

Reputation: 386

List classes in python file

Is there a way to get a list of all classes defined in a file?

for example: my_classes.py

class A:
  pass

class B:
  pass

class C:

main.py

import my_classes
classes(my_classes)

with some kind of result:

[<classObject A>, <classObject B>, <classObject C>]

Upvotes: 0

Views: 602

Answers (3)

Ehsan Popal
Ehsan Popal

Reputation: 11

You may import the module first, and then use:

import myfile
dir(myfile)

Upvotes: 1

Szymon Zmilczak
Szymon Zmilczak

Reputation: 383

Try that:

def classes(module):
    for item in module.__dict__.values():
        if isinstance(item, type):
            yield item

It depends on the fact that classes are actually instances of type.

Upvotes: 2

skullgoblet1089
skullgoblet1089

Reputation: 614

import mymodule

klasses = []
for objname in dir(mymodule):
    obj = getattr(mymodule, objname)
    if isinstance(obj, (type,)):
        klasses.append(obj)
        print(obj.__name__)

Upvotes: 0

Related Questions