I have the following 3 python files:
main.py
from .Constants import *
__init__.py
Constants.py
:
CONSTANT_TEST = test
Now when I run python3 main.py
i get the following error
ImportError: attempted relative import with no known parent package
Not sure what I am missing here.
The general rule of thumb is that you should never execute files from within the same package. My suggestion would be to create a test file and import your package into that file, then do all of your testing from within that file. For example, if your package directory looks like this:
package_tests.py
package/
__init__.py
main.py
Constants.py
In package/__init__.py
:
from package.Constants import CONSTANT_TEST
# import everything here that you want users to be able to access by topmost import ("import package")
In package/Constants.py
:
CONSTANT_TEST = "constant"
In package/main.py
:
from package.Constants import CONSTANT_TEST
# other code that utilizes CONSTANT_TEST
In package_tests.py
:
import package
print(package.CONSTANT_TEST)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.