开发者

Stumped by relative imports

I don't know what's going on:

$ ls
__init__.py  main.py  module.py
开发者_Python百科$ cat main.py
from . import module
$ python3 main.py
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from . import module
ValueError: Attempted relative import in non-package


From PEP 328:

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.

Clarification: The __name__ attribute will usually be the path a module has when it's being imported, e.g. in foo/bar.py, provided foo was the top-level package, __name__ would be 'foo.bar'. In the special case of a .py file you're running directly, __name__ evaluates to '__main__', which means relative imports will not work.


The error message is quite clear: You cannot do relative imports in your main script. See http://www.python.org/dev/peps/pep-0328/ for details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜