扁平包内相对进口

时间:2012-02-24 17:46:10

标签: python package

我有以下表格的包裹:

$ ls folder
entry_point.py  hello.py  __init__.py  utils.py

这是一个包,我可以这样对待它:

$ python2.7
>>> import folder.utils
>>>

我想在这些Python模块之间使用相对导入。

$ cat folder/entry_point.py 
from hello import say_hello

if __name__ == "__main__":
    say_hello()
$ cat folder/hello.py 
from .utils import say

def say_hello():
    say()
$ cat folder/utils.py
def say():
    print "hello world"

我知道我不能在入口处使用相对导入,我称之为解释器。但是,我仍然从导入的文件中获取ImportError

$ python2.7 folder/entry_point.py 
Traceback (most recent call last):
  File "folder/entry_point.py", line 1, in <module>
    from hello import say_hello
  File "/tmp/folder/hello.py", line 1, in <module>
    from .utils import say
ValueError: Attempted relative import in non-package

这是违反直觉的,它是一个包,由于entry_point.py将__name__设置为__main__(与PEP 328一致),因此不会将其视为一个包。

我很惊讶hello.py的__name__ hello而不是folder.hello。这使我无法在hello.py中使用相对导入。

如何在此包中使用相对导入?我是否被迫将hello.py和utils.py移动到libs子包?

1 个答案:

答案 0 :(得分:0)

如果您希望folder成为更大项目中的模块,并希望能够entry_point.py运行folder模块,请移动entry_point.py一个级别起来:

from folder.hello import say_hello

if __name__ == "__main__":
    say_hello()

Import paths - the right way?