Sign in to follow this  
crivens

Copy contents of one Python module to another?

Recommended Posts

crivens    182
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

Share this post


Link to post
Share on other sites
LorenzoGatti    4442
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).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this