Is it possible to use two Python packages with the same name?

前端 未结 4 1078
迷失自我
迷失自我 2020-12-11 02:38

I have a question about imports. The question might seem a bit contrived, but its purpose is to explore the limitations of using absolute imports for all imports in a packa

4条回答
  •  甜味超标
    2020-12-11 03:10

    My initial tests (in Python 2.6 & 3.1) suggest the following may work:

    import sys, re
    
    import foo as foo1
    for k in sys.modules:
        if re.match(r'foo(\.|$)', k):
            newk = k.replace('foo', 'foo1', 1)
            sys.modules[newk] = sys.modules[k]
            # The following may or may not be a good idea
            #sys.modules[newk].__name__ = newk
            del sys.modules[k]
    
    sys.path.insert(0, './python')
    import foo as foo2
    for k in sys.modules:
        if re.match(r'foo(\.|$)', k):
            newk = k.replace('foo', 'foo2', 1)
            sys.modules[newk] = sys.modules[k]
            # The following may or may not be a good idea
            #sys.modules[newk].__name__ = newk
            del sys.modules[k]
    

    However, I only tested this against very simple packages and only tried it as a curiosity. One problem is it probably breaks reload. Python isn't really designed to handle multiple packages with the same top-level name.

    At this point, I'm tentatively going to say that it's not possible in the general case, though it's possible under certain limited circumstances but it's very brittle.

提交回复
热议问题