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.
You can't import modules like that. import ..blah
is not valid import syntax. You need to do from .. import first_level
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With