Reputation: 386
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
Reputation: 11
You may import the module first, and then use:
import myfile
dir(myfile)
Upvotes: 1
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
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