I have a module that conflicts with a built-in module. For example, a myapp.email
module defined in myapp/email.py
.
I can reference myapp.email
anywhere in my code without issue. However, I need to reference the built-in email module from my email module.
# myapp/email.py from email import message_from_string
It only finds itself, and therefore raises an ImportError
, since myapp.email
doesn't have a message_from_string
method. import email
causes the same issue when I try email.message_from_string
.
Is there any native support to do this in Python, or am I stuck with renaming my "email" module to something more specific?
The easiest and most sane way to do it is to refactor you project and change the name of the file. There are probably some way strange way around this, but I would hardly consider that worth it, as it would most likely complicate your code, and make it prone to errors.
The ImportError is raised when an import statement has trouble successfully importing the specified module. Typically, such a problem is due to an invalid or incorrect path, which will raise a ModuleNotFoundError in Python 3.6 and newer versions.
You will want to read about Absolute and Relative Imports which addresses this very problem. Use:
from __future__ import absolute_import
Using that, any unadorned package name will always refer to the top level package. You will then need to use relative imports (from .email import ...
) to access your own package.
NOTE: The above from ...
line needs to be put into any 2.x Python .py
files above the import ...
lines you're using. In Python 3.x this is the default behavior and so is no longer needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With