3

If I import a module:

import foo

How can I find the names of the classes it contains?

Shep
  • 7,990
  • 8
  • 49
  • 71
tapioco123
  • 3,235
  • 10
  • 36
  • 42
  • are you just trying to learn how to use the class or are you looking for something like a `list` of names? – Shep Apr 15 '12 at 16:08

5 Answers5

9

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
obmarg
  • 9,369
  • 36
  • 59
3

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.

wim
  • 338,267
  • 99
  • 616
  • 750
1

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.

Jeroen
  • 1,168
  • 1
  • 12
  • 24
Chris
  • 44,602
  • 16
  • 137
  • 156
0

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)
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Shep
  • 7,990
  • 8
  • 49
  • 71
0

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)
silvado
  • 17,202
  • 2
  • 30
  • 46