Python module name conflict

主宰稳场 提交于 2019-12-01 03:56:29

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!