Python module name conflict

astrofrog picture astrofrog · May 9, 2011 · Viewed 7k times · Source

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

Answer

mouad picture mouad · May 9, 2011

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/).