class objects in dictionaries

Thomas Wouters thomas at xs4all.net
Sat Feb 5 11:53:52 EST 2000


On Sat, Feb 05, 2000 at 04:06:26PM +0000, mdvorak at ninell.cz wrote:

> I would like to put all my class definitions in a dictionary
> __objects__ in main global namespace. I know I can do it by
> putting the class objects into module called __objects__ and
> import this module, but that way classes would have different
> global namespace and I need them to have the same global
> namespace as the main script.

> I need to do something like:
> from class_objects import * to __objects__

> Is there any way in Python how to do this?

Well, yes. Create a module called __objects__ and do the imports there:

from prison import *
from rome import *

Of course, this does not import all classes (Those starting with a _ are
skipped) and it imports other things than classes as well. To have only
classes, you can either name all the classes on the import line:

from prison import you, lucky, bastard
from rome import biggus, dickus

Or you can create a real dictionary called __objects__, and
fill that with class objects only, automatically. Something like this:

from types import ClassType

def fill(objdict, modules):
	for module in modules:
		for item in dir(module):
			if type(module.__dict__[item]) == ClassType:
				objdict[item] = module.__dict__[item]

and call it at the appropriate place, like this:

>>> import mailbox 
>>> objects = {}
>>> fill(objects, [mailbox])
>>> objects
{'_Mailbox': <class mailbox._Mailbox at 80d6920>, '_Subfile': <class
mailbox._Subfile at 80d15e0>, 'BabylMailbox': <class mailbox.BabylMailbox at
80dea48>, 'MmdfMailbox': <class mailbox.MmdfMailbox at 80a7360>,
'UnixMailbox': <class mailbox.UnixMailbox at 80d68d0>, 'MHMailbox': <class
mailbox.MHMailbox at 80a90f0>}

But dont forget that changing some of the class objects on the fly
(replacing them with new classes), after the call to fill(), wont get them
changed in the self-made dict. (But the same goes for 'from <module> import
<name>'!) Altering classes in-place is safe, though.

Also, you might want to skip classnames starting with a _ (change the if in
fill() to look like this: if name[0] <> '_' and type(module.__dict__[item])
== ClassType: Just to keep this list of objects consistent with what 'from
foo import *' would give you.

Idle-hands--rhut-rho-ly y'rs
-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list