简体   繁体   中英

Import statement doesn't work as expected with Python 3.3

I recently ported a django application from Python 2.7 to Python 3.3 with Django1.6b1.

My import statements wouldn't work anymore for custom module imports (User, views...) and I had to add a dot before these imports. Why ?

Example :

import EmailUser #worked with python 2.7 but doesn't work with 3.3    
import .EmailUser #works    

Not a bug; Python 3 forces explicit relative imports.

From the docs :

The only acceptable syntax for relative imports is from .[module] import name . All import forms not starting with . are interpreted as absolute imports. ( PEP 0328 )

Also, import .EmailUser is invalid syntax in any Python version; it would have to be from . import EmailUser from . import EmailUser .

This is because of "absolute imports", that is the imports that do not start with . are absolute and must be found in module path. In Python 2.6, 2.7 you can turn this on file-by-file basis by doing

from __future__ import absolute_import

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM