python docsによると、相対インポートとパッケージ内参照は python 2.5 以降でサポートされています。現在、Python 2.7.3 を実行しています。そこで、より簡単にインポートできるように、これを自分のパッケージに実装しようとしました。SyntaxError 例外がスローされたことに驚き、誰かがその原因を突き止める手助けをしてくれることを期待していました。
テスト用のテスト ディレクトリをセットアップします。
tester
├── __init__.py
├── first_level.py
└── sub
├── __init__.py
└── second_level.py
両方の __init__.py モジュールが空です。他のモジュールは次のとおりです。
# 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"
second_level モジュールをインポートしようとすると、次のエラーが発生します。
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
2 行が次々に出力されると思っていましたが、代わりに例外が発生します。それで、私はインポートを間違っていますか?他にアイデアはありますか。