EDIT: A circular dependency issue was the reason why from .. import auth didn't work, see my own answer below. Cheers to all.
I'm dabbling with relative imports in Python while reorganizing some code and what should have taken 10 minutes is now taking untold amounts of time. Here's my file structure:
project/
/__init__.py
/application.py
/lib/
/__init__.py
/auth.py
/utils.py
/views/
/__init__.py
/login_view.py
/test.py
In login_view.py I have:
from . import auth
which yields: ImportError: cannot import name auth
However this works:
from ..auth import untoken, req_auth_or_error
Which I don't understand: auth is only one level above login_view, why the .. and not .?
This also fails with the same error:
from .. import auth
In test.py I tried the following:
import types
from .. import *
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
print 'imported: ', val.__name__
imports()
which results in:
imported: lib.utils
imported: lib.views
imported: types
... I'm at a loss as to why lib.auth is not imported. What am I doing wrong?
I'm running the code as such (the abs. path is /scratch/project/):
$ cd project/
$ ./application.py
The problem was a circular dependency one and not one of relative imports.
Indeed,
..is needed to load a module from the parent directory.However somewhere in
auth.pyI had animport views.login_view. I believe that thefrom .. import authinlogin_view.pytried to import theauthmodule as it was being loaded itself. This is probably whyfrom ..auth import untokenworks because those functions had already been loaded.