That is a great question! When you try to import a module that is not in the same directory as your script, Python will usually throw a ModuleNotFoundError.
However, there are a few ways to handle this:
1. The "Package" Way (Recommended)
If your module is in a subfolder, you can use dot notation.
Imagine your folder looks like this:
project/
│── main.py
└── tools/
├── __init__.py
└── math_operations.py
To use the module inside tools, you would write in main.py:
from tools import math_operations
# Or
import tools.math_operations
Note: The __init__.py file (even if empty) tells Python that the folder should be treated as a package.
2. Using sys.path (The "Manual" Way)
Python looks for modules in a list of folders called sys.path. You can manually add a folder path to this list at the very top of your script:
import sys
# Add the directory containing your module to the search path
sys.path.append('/home/labex/my_other_folder')
import math_operations
This tells Python: "Hey, if you can't find the module here, look in this other folder I just gave you."
3. The PYTHONPATH Environment Variable
You can tell your entire terminal session where to look for modules by setting an environment variable in Linux:
export PYTHONPATH=$PYTHONPATH:/home/labex/my_other_folder
After running this command, any Python script you run in that terminal will be able to find modules inside /home/labex/my_other_folder.
4. Installing it as a Library
For professional projects, developers create a setup.py or pyproject.toml file and install their own code using pip install -e .. This makes the module available globally on the system, regardless of which directory you are in.
Which scenario are you thinking of? Are you trying to organize your project into folders, or do you have a shared library in a completely different part of the system?