1

I don't know what's going on:

$ ls
__init__.py  main.py  module.py
$ 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
tshepang
  • 12,111
  • 21
  • 91
  • 136
  • Possible duplicate of [How to do relative imports in Python?](http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – kenorb Nov 05 '15 at 11:18

2 Answers2

4

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Mu Mind
  • 10,935
  • 4
  • 38
  • 69
0

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.

Achim
  • 15,415
  • 15
  • 80
  • 144
  • You mind explaining what the PEP says? I had a look and I'm still stumped. – tshepang May 07 '11 at 20:40
  • @Tshepang: I had the same problem finding what I was supposed to see in the PEP. See my answer for the direct link to the explanation (excerpted in my answer). – Mu Mind May 07 '11 at 20:44
  • 1
    `ValueError: Attempted relative import in non-package` is not exactly clear. Are you sure you aren't taking your knowledge for granted? – tshepang May 07 '11 at 21:04