how to find available classes in a file ?

Gabriel Genellina gagsl-py2 at
Tue Jul 17 18:26:50 CEST 2007

En Tue, 17 Jul 2007 11:05:17 -0300, Alex Popescu  
<the.mindstorm.mailinglist at> escribió:

> On Jul 17, 4:41 am, "Gabriel Genellina" <gagsl-... at>
> wrote:
>> > On Jul 17, 1:44 am, Stef Mientki <S.Mientki-nos... at>
>> > wrote:
>> >> I want to have a (dynamically) list of all classes defined in a  
>> py-file.
>> inspect.getmembers(the_module, inspect.isclass) would do. But this
>> requires the module to be importable.
> I may be wrong but I think I've found a difference between my
> dir(module) approach
> and the inspect.getmembers(module, inspect.isclass): the first one
> returns the
> classes defined in the module, while the later also lists the imported
> available
> classes.

Let's try, using the standard module which imports class Chunk  

py> import inspect
py> import wave
py> inspect.getmembers(wave, inspect.isclass)
[('Chunk', <class chunk.Chunk at 0x00ADEC00>), ('Error', <class  
'wave.Error'>), ...
py> dir(wave)
['Chunk', 'Error', 'WAVE_FORMAT_PCM', 'Wave_read', 'Wave_write', ...

Chunk appears on both. (That's not a surprise, since inspect.getmembers  
uses dir() internally).
If you want to include *only* classes defined in the module itself, you  
could test the __module__ attribute:

py> wave.Chunk.__module__
py> wave.Wave_read.__module__

How to filter when the class is defined deeply inside a package is left as  
an exercise to the reader :)

Gabriel Genellina

More information about the Python-list mailing list