Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Module Imports - Explicit vs Implicit Relative Imports

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?

like image 273
William Avatar asked Dec 20 '13 14:12

William


1 Answers

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'
like image 189
Paulo Bu Avatar answered Nov 15 '22 22:11

Paulo Bu