How to do wierd imports in python

Normally, you can't import two different modules with the same name. You can work around this with the imp module (http://docs.python.org/lib/module-imp.html).

Each module has a key in sys.modules (a dictionary). This is just reference to the module, you can delete it and it won't do anything bad. I don't know if it will be garbage collected if all references are removed. sys.modules is where it looks to see if it should re-import/return a reference something when you do import something.

You can do specific imports like this:

mod1a = imp.load_module("mod1a",                  # NAME
                        file("../mod1.py", "U"),  # FILE OBJECT
                        "../mod1.py",             # FILENAME
                        ('.py','U', 1)            # DESC
                        )

So, to import stuff specially, you assign the returned module object (mod1a above) to some different name, and change at least NAME (optional if take care of sys.modules), FILE OBJECT, and probably FILENAME (for debugging)

wait: you should look at load_source. It automatically does byte-compiling logic. Basically, an easier way to do the above (you only give the parameters you need, not all the other junk).

Python/Importing (last edited 2008-03-10 01:38:53 by localhost)