nightmare with relative imports, how does pep 366 work?

后端 未结 4 622
無奈伤痛
無奈伤痛 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:18

    This is a minimal setup based on most of the other answers, tested on python 2.7 with a package layout like so. It also has the advantage that you can call the runme.py script from anywhere and it seems like it's doing the right thing - I haven't yet tested it in a more complex setup, so caveat emptor... etc.

    This is basically Brad's answer above with the insert into sys.path others have described.

    packagetest/
      __init__.py       # Empty
      mylib/
        __init__.py     # Empty
        utils.py        # def times2(x): return x*2
      scripts/
        __init__.py     # Empty
        runme.py        # See below (executable)
    

    runme.py looks like this:

    #!/usr/bin/env python
    if __name__ == '__main__' and __package__ is None:
        from os import sys, path
        d = path.dirname(path.abspath(__file__))
        __package__ = []
        while path.exists(path.join(d, '__init__.py')):
            d, name = path.split(d)
            __package__.append(name)
        __package__ = ".".join(reversed(__package__))
        sys.path.insert(1, d)
        mod = __import__(__package__)
        sys.modules[__package__] = mod
    
    from ..mylib.utils import times2
    
    print times2(4)
    

提交回复
热议问题