12

According to the python docs, relative importing and intrapackage referencing has been supported since python 2.5. I am currently running Python 2.7.3. So, I tried to implement this in my own package in order to use it for simpler importing. I was surprised to find it threw a SyntaxError exception at me, and I was hoping someone could help lead the way to the cause.

I setup a test directory for testing:

tester
├── __init__.py
├── first_level.py
└── sub
    ├── __init__.py
    └── second_level.py

Both __init__.py modules are empty. The other modules are:


# first_level.py
print "This is the first level of the package"

# sub/second_level.py
import ..first_level
print "This is the second level"

When I attempt to import the second_level module, I get the following error:

Python 2.7.3 (default, Aug  1 2012, 14:42:42) 
[GCC 4.2.1 Compatible Apple Clang 4.0 ((tags/Apple/clang-421.0.57))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Welcome!
>>> import tester
>>> import tester.sub.second_level
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tester/sub/second_level.py", line 1
    import ..first_level
           ^
SyntaxError: invalid syntax

I expected the two lines to print one after the other, but it raises an exception instead. So, am I doing the import wrong? Do you have any other ideas.

0

1 Answer 1

17

You can't import modules like that. import ..blah is not valid import syntax. You need to do from .. import first_level.

Sign up to request clarification or add additional context in comments.

4 Comments

Base on the official documenation this IS VALID syntax in case the blah is a package. Check the example from the link above and namely from ..filters import equalizer where filters is a package and equalizer - a module. You should not generalize like that.
@rbaleksandar: No, the example uses from. from ..blah import stuff is valid. import ..blah is not. You can only use dot-notation relative imports with the from form of import (as mentioned in the documentation you linked to).
I know that but your comment can be read as a general conclusion. You should add something like "In your case you can't import ... because ...".
I still got a "misleading" syntax error on the import line, but it turned out the syntax error was inside the file I tried to import and not on the actual import line. Just something to keep in mind :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.