Python Module Imports - Explicit vs Implicit Relative Imports

若如初见. 提交于 2019-12-22 03:17:11

问题


Last night, when working on my mac, I set up some module imports in my __init__.py's

from MongoProvider import MongoProvider
from Settings import Settings

etc. I'm unsure of what version of Python is on that machine. I'll edit the question later with that info once I have it.

Today, working on a different machine, which is Windows and using Python 3.3.3, my module imports were breaking. By adding an explicit relative import (adding a leading dot), I was able to fix the issue.

from .MongoProvider import MongoProvider
from .Settings import Settings

The trace I'm receiving is:

Traceback (most recent call last):
File "app.py", line 5, in <module> from modules.route_handlers import Route_Handlers
File "C:\Users\willb\bearded-dubstep\modules\route_handlers\Route_Handlers.py", line 9, in <module> from modules.backend_providers import Settings
File "C:\Users\willb\bearded-dubstep\modules\backend_providers\__init__.py", line 1, in <module> from MongoProvider import MongoProvider
ImportError: No module named 'MongoProvider'

My Project Layout is

root
|_modules
  |_api_helpers
    |  __init__.py
    |  InvalidUsage.py
    |  response_utils.py
  |_backend_providers
    |  __init__.py
    |  MongoProvider.py
    |  Settings.py
  |_route_handlers
    |  __init__.py
    |  Route_Handlers
|  app.py

Any ideas what would cause this? Is there a configuration file I should be looking at?


回答1:


Well, according to PEP-8 imports section:

Implicit relative imports should never be used and have been removed in Python 3.

As Python 3.3 is the one causing you trouble, making you explicit import relatives modules, I assume this explains the situation. It's probably that on Mac you have Python 2.x, that's why it works there.

Looking at your project's file distribution, Settings.py and MongoProvider are indeed relative modules. This means that the removal of implicit relative imports in Python 3 is the one causing you trouble, because the import system is unable to find the module:

ImportError: No module named 'MongoProvider'



回答2:


It seems that the Python Version on your mac is 2.x while the Python on your windows is 3.x.

I have met the same problem before using module tkinter (which is Tkinter in Python 2.x).

It seems that we need to use from XXX.xxx import xxx to import...●﹏●

I don't know why, maybe it's the designer's adjusting to Python.



来源:https://stackoverflow.com/questions/20706335/python-module-imports-explicit-vs-implicit-relative-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!