3

If I import a module:

import foo

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

Shep
  • 7,474
  • 5
  • 44
  • 69
tapioco123
  • 2,985
  • 8
  • 33
  • 40
  • 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,159
  • 34
  • 58
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
  • 302,178
  • 90
  • 548
  • 690
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,162
  • 1
  • 11
  • 22
Chris
  • 42,054
  • 16
  • 135
  • 151
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,250
  • 13
  • 64
  • 126
Shep
  • 7,474
  • 5
  • 44
  • 69
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
  • 15,242
  • 2
  • 27
  • 46