When you try to import a module with the same name as the built-in module, an import error occurs

I have a module that conflicts with the built-in module. For example, the myapp.email module defined in myapp/email.py .

I can reference myapp.email anywhere in my code without any problems. However, I need to access 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 ImportError since myapp.email does not have a message_from_string method. import email causes the same problem when I try email.message_from_string .

Is there any built-in support for this in Python, or am I stuck in renaming my email module to something more specific?

+61
python python-import
Aug 03 '09 at 21:34
source share
1 answer

You want to read about Absolute and relative imports that solves this problem. Using:

 from __future__ import absolute_import 

Using this, any unvarnished package name will always refer to a top-level package. Then you will need to use relative imports ( from .email import ... ) to access your own package.

NOTE. . The above line from ... should be placed in any Python .py files 2.x above the import ... lines you use. In Python 3.x, this is the default behavior and therefore is no longer required.

+89
Aug 03 '09 at 21:38
source share
β€” -



All Articles