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
The easiest and most sane way to do it is to refactor you project and change the name of the file. There are probably some way strange way around this, but I would hardly consider that worth it, as it would most likely complicate your code, and make it prone to errors.
Name clashes can occur, for example, if two or more Python modules contain identifiers with the same name and are imported into the same program, as shown below: In this example, module1 and module2 are imported into the same program. Each module contains an identifier named double, which return very different results.
from __future__ import absolute_import means that if you import string , Python will always look for a top-level string module, rather than current_package.string . However, it does not affect the logic Python uses to decide what file is the string module.
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/).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With