Binding the names in a module in a class instance

J

Jacob H

Hello all,

I would like to be able to take a module full of class instances,
functions, etc and bind all its names to a separate container class in
a different module. I have come up with the following way to do it..

(module "globals")

class Container:
pass
container = Container()

(module "all_the_stuff")

....define a bunch of stuff...

(module "main")

exec open("all_the_stuff.py").read() in globals.container.__dict__

I feel uneasy about this method. I foresee bad namespace clashes.
What's a better way? :)

Thanks in advance,
Jacob
 
N

Neal Norwitz

Jacob said:
Hello all,

I would like to be able to take a module full of class instances,
functions, etc and bind all its names to a separate container class in
a different module. I have come up with the following way to do it..
[snip]

I feel uneasy about this method. I foresee bad namespace clashes.
What's a better way? :)

Perhaps this is more like what you are looking for:

import stuff # stuff we want to copy
import everything # initially empty module where to store stuff

# loop over each attribute name in stuff
for attr in dir(stuff):
# skip over __special__ attributes, probably don't want them
if attr.startswith('__') and attr.endswith('__'):
continue

value = getattr(stuff, attr)
setattr(everything, attr, value)

You can add more checking for clashes or whatever by looking at the
attribute name (attr) which is a string.

hth,
n
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top