I have come across two Python modules that have to be imported using the same module name, e.g.
import foo
I know that the one I want provides certain functions (e.g. foo.bar()
), so is there a way to cycle through the modules with the same name until I find the one that provides those functions? Or is there no way around other than renaming the module before installing?
Edit: just to clarify what I mean, both modules are inside site-packages:
site-packages$ ls python_montage-0.9.3-py2.6.egg
EGG-INFO montage
site-packages$ ls montage-0.3.2-py2.6.egg/
EGG-INFO montage
Here is a way :
import imp
import sys
def find_module(name, predicate=None):
"""Find a module with the name if this module have the predicate true.
Arguments:
- name: module name as a string.
- predicate: a function that accept one argument as the name of a module and return
True or False.
Return:
- The module imported
Raise:
- ImportError if the module wasn't found.
"""
search_paths = sys.path[:]
if not predicate:
return __import__(name)
while 1:
fp, pathname, desc = imp.find_module(name, search_paths)
module = imp.load_module(name, fp, pathname, desc)
if predicate(module):
return module
else:
search_paths = search_paths[1:]
I bet there is some corners that i didn't take in consideration but hopefully this can give you some idea.
N.B: I think the best idea will be to just rename your module if possible.
N.B 2: As i see in your edited answer, sadly this solution will not work because the two modules exist in the same directory (site-packages/).
There are ways to hack around the two modules with the same name limitation, but unless you are doing this simply for educational purposes, I wouldn't recommend it. The end result will be confusing and unmaintainable. I highly recommend renaming one or both of the modules instead of messing around with obscure Python import related features.
Since python 2.5 (and PEP 328) absolute import is the prefered way of managing modules in python. In your case, your module tree is certainly like this :
/src/first_level/foo
/other_foo
/second_level/foo # with the bar method
If you want to use the foo module with the bar method, use this :
import second_level.foo
If you're happy that you can figure out the filenames through some other heuristic, then you should be able to use imp.load_module to load them separately.
See http://docs.python.org/library/imp.html#imp.load_module
In your case, although both eggs are on the python path, I believe eggs do some magic whereby each egg acts as a path. You might be able to set the egg file as the path argument to imp.find_module
in order to load them separately.
来源:https://stackoverflow.com/questions/5937739/python-module-name-conflict