I haven't come across this problem yet, but I'm curious about how to import a module that has the same name as a sub-package. For instance, a possible module-structure could look like this:
mymodule\
__init__.py
string.py
Now, what if I need the mymodule.string subpackage and the string module that is delivered with every Python distribution from a package that is within the same directory, such as __init__.py? The following lines of code all import the subpackage.
from . import string
import mymodule.string as string
import string
In Python 2.5 or 2.6, you can use:
>>> from __future__ import absolute_import
Which tells Python that all imports that aren't explicitly relative should be treated as absolute. I.e., after using this declaration, you can access both the builtin string module and your own string module using:
>>> import string as the_builtin_string_module
>>> from . import string as my_package_string_module
I believe that this becomes the default in Python 2.7 (and Python 3.0).
For more info, see: http://www.python.org/dev/peps/pep-0328/#rationale-for-absolute-imports
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