[Tutor] listing classes

Kent Johnson kent37 at tds.net
Tue May 20 19:48:03 CEST 2008


On Tue, May 20, 2008 at 12:47 PM, Thomas Pani <thomas.pani at gmail.com> wrote:
> Hi,
>
> dir(A) will essentially give you what you want (and a little more)
>
> If you're only interested in classes, you can do something like:
>
> import types
> [ name for name in dir(A) if type(eval('A.'+name)) == types.ClassType ]

There is no need to use eval() here. Python has powerful introspection
capabilities - use getattr() to get a named attribute of an object.
For example:

In [1]: class A:
   ...:     class B:
   ...:         pass
   ...:     class C:
   ...:         pass

In [2]: dir(A)
Out[2]: ['B', 'C', '__doc__', '__module__']

In [3]: type(A.B)
Out[3]: <type 'classobj'>

In [4]: type(A)
Out[4]: <type 'classobj'>

In [5]: [ name for name in dir(A) if type(getattr(A, name))==type(A) ]
Out[5]: ['B', 'C']

Note: types.ClassObj is the type of old-style classes. The OP used
new-style classes which are of type type. Using type(A) for the
comparison means it will work with either kind of classes as long as
they are the same. You could also use inspect.isclass() to decide if
it is a class.

Kent


More information about the Tutor mailing list