How to import python module with same filename tha

2020-02-07 03:29发布

问题:

I have a problem with python module import. I installed django (this can be any other module). I use this module:

from django.template import Context
# other imports
# use Context

I have a folder in my application named "utilities". In this folder I created a file "django.py" - this file contains some functions to work with django. So I import django in my module and I get error: File "...\utilities\django.py", line 1, in from django.template import Context ImportError: No module named template

回答1:

You will have to enable absolute imports at the top of the file:

from __future__ import absolute_import

You will then have to convert the imports in the module into absolute or relative imports as appropriate.



回答2:

Use namepaces, create a __init__.py in your utilities directory, so that it is package and then do import utilities.django. Btw, it is bad practice to name your module the same as std libraries or the name of package you know you are going to use. You never know when you are going to confuse yourself with which module to use.