0

Let's say I have modules foo.py and bar.py and both have import baz statement in their code.

I want to write an import hook that I can insert into sys.meta_path that knows whether baz is being imported from foo or from bar.

The reason why I want to do this is because I want my app to be able to load plugins and keep their dependencies isolated, the way I would be able to by using separate ClassLoader instances in Java. That way, plugin foo and plugin bar would be able to bundle different versions of library baz without conflict. The way I mean to accomplish that is by changing the import mechanism to produce separate modules for import baz statement depending on where that statement comes from.

If anyone has a better way of doing this, feel free to suggest it in your answer.

Vojislav Stojkovic
  • 8,043
  • 4
  • 35
  • 48
  • Don't do it. Python modules are singletons, and doing that you are breaking this invariant which may lead to a lot of troubles(maybe unexpected) later. You may be able to bundle all the state that you need in a class and use an instance of the class instead of the module.(e.g. `import baz; mybaz = baz.create_state()`) – Bakuriu Dec 02 '12 at 17:40
  • You're missing the point. I could do that if `baz` were guaranteed to be my module, but what is `baz` is someone else's library, like PyYAML or sh? Each module would remain a singleton from the point of view of separate plugins. I'm not going to instantiate a new module every time someone tries to import it. – Vojislav Stojkovic Dec 02 '12 at 20:22
  • PEP 302 hooks were introduced to allow importing from non-standard formats(see "use cases" section of the PEP), they are **not** intended to create multiple copies of the same module. Using them for something they were not designed for will probably bite you at some point. Anyway, you might be interested in the [`inspect`](http://docs.python.org/2/library/inspect.html) module to get the information about which module is doing the import, in particular the stack-related functions. – Bakuriu Dec 02 '12 at 20:43

0 Answers0