Finding all classes in a module

Delaney, Timothy tdelaney at avaya.com
Mon Aug 12 09:32:42 CEST 2002


> From: Mark McEahern [mailto:marklists at mceahern.com]
> 
> > The replies you got so far only seem to work for old-style classes:
> 
> [snip]
> 
> Good point.  Here's another approach:
> 
>   # junk.py
>   class foo:pass
>   class bar(object):pass
> 
> Then:
> 
>   >>> import junk
>   >>> import inspect
>   >>> inspect.getmembers(junk, inspect.isclass)
>   [('bar', <class 'junk.bar'>), ('foo', <class junk.foo at 
> 0x10102d28>)]

Remember that this will only work for classes defined in the module
namespace. Classes defined within other classes (*not* within a method) will
not be found - you will need to inspect recursively.

Tim Delaney




More information about the Python-list mailing list