Copy contents of one Python module to another?

Started by
2 comments, last by crivens 15 years, 11 months ago
I create a temporary module:
scratch = imp.new_module("scratch")
scratch.__file__ = "scratch.py"
sys.modules["scratch"] = scratch

If I load a Python source file into a temporary module using:
imp.load_source("scratch", fn)
Is it possible to somehow copy the contents of scratch into a different module? I'm loading several python files, each one can contain 0..n Python classes. I want to load them all into the same module called (for argument's sake) "data" at runtime. But I want to add the classes from each file to different lists. I thought I could use load_source to load the classes from one file into a temporary module, add them to the list and then copy them into the data module. I can't see how to do this or I can't see any better ways of doing this. I want to load and instantiate classes at runtime to make the application logic configurable at startup. If that makes sense. Any suggestions? Thanks
Advertisement
Perhaps the deepcopy functionality will suffice?
If I understand correctly, you have several files with scripts consisting of class definitions, you want the classes to belong to the same module, and you want a "list" of which script piece these classes come from.

Maybe you can simply execfile() the scripts from the module's definition, providing to the scripts some object that can register class definitions (e.g. a decorator that knows where the class should be listed).

Omae Wa Mou Shindeiru

Thanks for the suggestions - I'll look into those.

This topic is closed to new replies.

Advertisement