Issue
I have a Django project (Python 2.7.15) with the following structure:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
utils.py
utils/
__init__.py
filters.py
In my utils/filters.py
file I have a class MyFilter
. From polls/admin.py
, however, when I try to run from utils.filters import MyFilter
, I get ImportError: No module named filters
. How can I import my custom filter inside the polls app without renaming the polls/utils.py
module or the utils
package?
NOTE: This it's not a circular import problem. This happens even if I don't import anything from utils/filters.py
. It's a name conflict between utils/
and polls/utils.py
. Python tries to find filters.MyFilter
inside polls/utils.py
and it doesn't find it so it throws the error. I just want to figure out a way to bypass this conflict and force python to look for filters.MyFilter
inside the utils/
package in the project root.
Solution
In Python 2, import utils
is ambiguous because it can be a relative or an absolute import.
If you enable the Python 3 behaviour by adding the following import to the top of your module,
from __future__ import absolute_import
then from utils.filters import MyFilter
will be treated as an absolute import and will work.
Once you have added the future import, you would need to use an explicit relative import import .utils
if you wanted to import polls/utils.py
from polls/admin.py
.
Answered By - Alasdair
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.