How to import Python from relative path

For example, we have a file with the following structure:


if we want to call in libs/ module, such as using relative call: from.. 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 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('..'))

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.


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
        from ..libs.some_lib import something

Read More: