how to find available classes in a file ?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jul 17 18:26:50 CEST 2007


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

> On Jul 17, 4:41 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> > On Jul 17, 1:44 am, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl>
>> > 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 wave.py which imports class Chunk  
 from chunk.py:

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__
'chunk'
py> wave.Wave_read.__module__
'wave'

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