For example, we have a file with the following structure:
pkg/
__init__.py
libs/
some_lib.py
__init__.py
components/
code.py
__init__.py
if we want to call in
module, such as using relative call: code.py
libs/some_lib.pyfrom.. Libs.some_lib import something
, it is not enough simply to add /___ to the package. Py
. Python returns the error ValueError: first import in non-package
. So how do you solve this problem?
has the following solution:
Add the current path to sys.path
considering that compontent
and libs
are folders at the same level, we can add the following code directly in code.py
to add the parent folder of the current folder to the system path.
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
or the following (this is true for any relational folder, as long as we give the absolute path to the folder in lib_path
) :
import os, sys
lib_path = os.path.abspath(os.path.join('..'))
sys.path.append(lib_path)
so we can import something with from libs.some_lib import something
.
executes the code in package
mode:
python -m pkg.components.code
and then we can use from.. Libs.some_lib import something
to import.
note that you don’t need .py
to end the file.
summary h2>
we can actually combine these two approaches:
if __name__ == '__main__':
if __package__ is None:
import sys
from os import path
sys.path.append( <path to the package> )
from libs.some_lib import something
else:
from ..libs.some_lib import something
div>