type(), modules: clarification please

Chris Rebert clp2 at rebertia.com
Sat Oct 15 19:18:46 EDT 2011


On Sat, Oct 15, 2011 at 4:00 PM, Shane <gshanemiller at verizon.net> wrote:
> Hi,
>
> When one writes,
>
>> className='Employee'
>> baseClasses = ...
>> dictionary = { ... }
>> newClass = type( className, <baseClasses>, dictionary)
>
> in what module does newClass belong? If it's the current module

That does seem to be the case.

> what code
> do I run to print out the name of that module in a.b.c... form?

newClass.__module__ is a string containing the (apparently) qualified
name of the module wherein newClass was defined.

<snip>
> Final question. If, as an academic exercise I wanted to recursively
> dump
> all the classes in a module (and its sub-modules) would I do this? [I
> use
> some pseudo code]:
>
> def dump( namespace ):
>       for i in dir(namespace):
>              if i is a class:
>                   print i
>              elif i is a module:
>                   dump(i)
>
> dump( <top-level-module> )

Pretty much, though `i` is just a string, so you'll need to use
getattr() to get the actual value of the corresponding variable. You
may also need to watch out for circular references so that your
function doesn't get stuck in an infinite loop.
FYI, `inspect` module had functions to test for class-ness and
module-ness. http://docs.python.org/library/inspect.html

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list