nightmare with relative imports, how does pep 366 work?

后端 未结 4 620
無奈伤痛
無奈伤痛 2020-12-13 06:35

I have a \"canonical file structure\" like that (I\'m giving sensible names to ease the reading):

mainpack/

  __main__.py
  __init__.py 

  - helpers/
              


        
4条回答
  •  死守一世寂寞
    2020-12-13 07:14

    The loading code seems to be something like this:

        try:
            return sys.modules[pkgname]
        except KeyError:
            if level < 1:
                warn("Parent module '%s' not found while handling "
                     "absolute import" % pkgname, RuntimeWarning, 1)
                return None
            else:
                raise SystemError, ("Parent module '%s' not loaded, cannot "
                                    "perform relative import" % pkgname)
    

    which makes me think that maybe your module is not on sys.path. If you start Python (normally) and just type "import mainpack" on the prompt, what does it do? It should be able to find it.

    I have tried it myself and got the same error. After reading a bit I found the following solution:

    # foo/__main__.py
    import sys
    mod = __import__('foo')
    sys.modules["foo"]=mod
    
    __package__='foo'
    from .bar import hello
    
    hello()
    

    It seems a bit hackish to me but it does work. The trick seems to be making sure package foo is loaded so the import can be relative.

提交回复
热议问题