简体   繁体   中英

Python import works in 2.7 but fails in 3.2+

Importing a package with:

from unique_upload import unique_file_upload

Works in Python 2.7 but fails in Python 3.2 and above with:

ImportError: cannot import name unique_file_upload

The project structure is:

test/ 
   __init__.py
   test_unique_upload # <-- calling from unique_upload import unique_file_upload here

 unique_upload/ 
      __init__.py
      unique_upload

unique_upload/__init__.py contains:

__version__ = '0.2.0'
from unique_upload import unique_file_upload

Full stack trace:

ImportError: Failed to import test module: test_unqiue_upload
Traceback (most recent call last):
  File "/opt/python/3.5.0/lib/python3.5/unittest/loader.py", line 428, in _find_test_path
    module = self._get_module_from_name(name)
  File "/opt/python/3.5.0/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name
    __import__(name)
  File "/home/travis/build/agconti/django-unique-upload/test/test_unqiue_upload.py", line 4, in <module>
    from unique_upload import unique_file_upload
  File "/home/travis/build/agconti/django-unique-upload/unique_upload/__init__.py", line 2, in <module>
    from unique_upload import unique_file_upload
ImportError: cannot import name 'unique_file_upload'

Any idea why this is happening?

It seems you are facing one of the incompatible change of Python: Relative imports , aka PEP 328.

This should work:

from .unique_upload import unique_file_upload

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