In my django application I have an app called projects and and app called utils. I also have a module inside projects called utils to hold helper functions for just projects.
So my file structure would look something like this
...
projects/
utils/
globals.py
views.py
utils/
tests.py
...
I ran into a problem when I tried to import something from utils (outer one) and django thought I was importing from projects.utils. So this gave me an error
# inside projects.views.py
from utils.tests import foo
Since I don’t have tests.py in projects.utils, the import gave me an error. Of course, I knew that and was trying to reference the outer utils.
Is there a way to reference both the outer utils and the projects.utils clearly in django or should I just change the name of projects.utils to something else?
By default, an
import utilscall in modules directly contained in theprojectspackage will try a relative import first and pick upprojects.utils.The easiest method would be to turn on absolute imports via the following pragma at the top of your module:
This turns off this implicit relative import behaviour (which also makes it match Python 3), so
import utilswill always pick the top level module. Note that the pragma will only affect imports within the file it occurs: if you want the behaviour in multiple modules, you will need to include the pragma in each file.You can still perform relative imports in this mode, but you will have to be explicit: