Python relative imports within a package not on the path

前端 未结 2 2076
北恋
北恋 2021-01-13 15:28

How can I import a file that is in a parent directory within a python package (that is not on the path) into a file in a child dir?

I\'m not totally clear on the voc

2条回答
  •  半阙折子戏
    2021-01-13 16:12

    The answer is in the link you gave:

    Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

    You cannot do relative imports in __main__ scripts (i.e. if you directly run python in_dir2.py).

    To solve this, what PEP 366 allows you to do is set the global __package__:

    import dir1
    if __name__ == '__main__':
        __package__ = 'dir1.dir2'
        from .. import in_dir1
    

    Note that the package dir1 still has to be on sys.path! You can manipulate sys.path to achieve this. But by then, what have you achieved over absolute imports?

提交回复
热议问题