Cory Cory -4 years ago 63
Python Question

Trying to import module with the same name as a built-in module causes an import error

I have a module that conflicts with a built-in module. For example, a
module defined in

I can reference
anywhere in my code without issue. However, I need to reference the built-in email module from my email module.

# myapp/
from email import message_from_string

It only finds itself, and therefore raises an
, since
doesn't have a
import email
causes the same issue when I try

Is there any native support to do this in Python, or am I stuck with renaming my "email" module to something more specific?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download