Reputation: 3545
If I import a module:
import foo
How can I find the names of the classes it contains?
Upvotes: 3
Views: 512
Reputation: 46366
From the question How to check whether a variable is a class or not? we can check if a variable is a class or not with the inspect
module (example code shamelessly lifted from the accepted answer):
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
So to build a list with all the classes from a module we could use
import foo
classes = [c for c in dir(foo) if inspect.isclass(getattr(foo, c))]
Update: The above example has been edited to use getattr
(foo, c)
rather than use foo.__getattribute__(c)
, as per @Chris Morgan's comment.
Upvotes: 1
Reputation: 8380
You can get a lot of information about a Python module, say foo, by importing it and then using help(module-name) as follows:
>>> import foo
>>> help(foo)
Upvotes: 0
Reputation: 9569
You can use the inspect module to do this. For example:
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print name
Upvotes: 9
Reputation: 18197
You can check the type of elements found via dir(foo)
: classes will have type type
.
import foo
classlist = []
for i in dir(foo):
if type(foo.__getattribute__(i)) is type:
classlist.append(i)
Upvotes: 0
Reputation: 363556
Check in dir(foo)
. By convention, the class names will be those in CamelCase.
If foo
breaks convention, you could I guess get the class names with something like [x for x in dir(foo) if type(getattr(foo, x)) == type]
, but that's ugly and probably quite fragile.
Upvotes: 3