2

I see many people use the following import methods in their projects:

from .module1 import a,b
from ..module2 import *

The module1 and module2 are a .py file but not a folder for package. What's the differences to the import module? Does it mean to import the module in current and ../ folder? But when I try to import another file in same folder, it said:

import .other
>>> SyntaxError: Invalid syntax
from .other import *
>>> ValueError: Attempted relative import in non-package

I'm curious on it. Thanks~

platinhom
  • 139
  • 10

1 Answers1

4

What you see is relative imports. They allow you to import modules by specifying their relative paths, without hard-coding the name of the package in which the modules are defined.

Does it mean to import the module in current and ../ folder?

Yes.

See PEP 328 for more details. Note it says:

Relative imports must always use from <> import; import <> is always absolute.

which is why you get the SyntaxError when trying import .foo.

The ValueError is probably because you are running the importing file as a script (and it used to confuse me a lot). You need to run it as a package (using the -m switch) for relative imports to work. That is, suppose foo.py relative-imports other modules, you can't run it by

$ python foo.py  # non-package error

Instead you do

$ python -m foo

See the related question: How to do relative imports in Python.

Community
  • 1
  • 1
gil
  • 2,086
  • 12
  • 13
  • Thanks~ I'm the first time to know `relative import`. I tried the test in the interpreter using `import a` which contains `from .other import *`. So it's not the `__main__` in this situation. Also I try the `python -m a` even a new script b (containing `import a`) for `python -m b`. It still raises the same ValueError... – platinhom Feb 11 '16 at 20:15
  • @platinhom Can you lay out your directory structure in OP? – gil Feb 11 '16 at 20:32
  • The directory structure is : a.py, b.py, and other.py are all in the same folder. I add a __init__.py in this folder to make it looks like a package. But run the b.py (`import a`) still don't work. But, when I move the b.py to upper folder (`b.py`, `test/a.py`, `test/other.py`, `test/__init__.py`) and modify b.py to `import test.a`, the `from other import *` works! It seems like that it's necessary to make `a.py` as a module in a package. – platinhom Feb 11 '16 at 20:51
  • @platinhom That's right, the file you run must be inside a package (as `-m` should make clear). BTW, if you are on Python 3, `__init__.py` is not necessary for declaring a package, although some people like to have it anyway. – gil Feb 11 '16 at 20:54
  • Thanks. I am still a little confused with their concepts but I will further check it~ – platinhom Feb 11 '16 at 23:05