[Python]“from modulename import *” in Python2 and Python3
Tell you how to use the same code to run in Python 2 and 3.
Background
After packing my module to wheel, I started to test it and found that the code below couldn’t run in Python 3 but it’s fine in Python 2.
from modulename import *
This is the folder structure
modulename
├── __init__.py
└── modulename.so
modulename.so is the file providing functionalities and I needed to wrap some class names as another. The __init__.py is like this:
from modulename import *
ClsPublic = ClsPersonal # export it as ClsPublic
Then the import error came out. So frustrating!
Solution
The fact is there are some differences between Python2 and Python3 on importing module.
If you try to print the module path, you would be surprised that you get the totally different path.
import modulename
print(modulename) # Leading different results.
The reason is
- Python 2 supports implicit relative imports. Python 3 does not.
- Python 2 requires
__init__.py
files inside a folder in order for the folder to be considered a package and made importable. In Python 3.3 and above, thanks to its support of implicit namespace packages, all folders are packages regardless of the presence of a__init__.py
file. - In Python 2, one could write
from <module> import *
within a function. In Python 3, thefrom <module> import *
syntax is only allowed at the module level, no longer inside functions.
From: https://www.python.org/dev/peps/pep-0404/
The most important part — Solution
- using six
import six
if six.PY2:
from modulename import *
else:
from modulename.modulename import *
2. Explicitly site the path
import .modulename import *
Reference