In this lesson, you will learn how to help Python find your custom modules by manually updating the sys.path list.
Why Python Can't Find Your Module
When you use an import statement, Python searches for the module in a specific list of directories. You can see this list by importing the sys module and printing sys.path. If your script is in a different folder than the module you are trying to import, Python will throw a ModuleNotFoundError because it isn't "looking" in your custom directory.
Inspecting and Modifying sys.path
The sys.path variable is just a standard Python list of strings, where each string is a file system path. Because it is a list, you can use familiar methods like .append() or .insert() to add your own directory to the search order.
Imagine you have a project structure like this:
/my_project/main.py/my_project/libs/helper.py
If main.py tries to import helper, it will fail because libs/ isn't in the default path. You can fix this at the top of main.py:
import sys
import os
# Identify the absolute path to the directory containing your module
module_dir = os.path.abspath("libs")
# Add the directory to sys.path if it isn't already there
if module_dir not in sys.path:
sys.path.append(module_dir)
# Now Python knows where to look!
import helper
Best Practices
When you call sys.path.append(), you are telling Python to check your custom directory as a last resort. If you need your module to be found before other system libraries, you could use sys.path.insert(0, path) instead, which places your directory at the very beginning of the search list.
Be careful: modifying sys.path is powerful, but it should be done sparingly. It is best to perform this at the very top of your script (ideally inside your main guard) so that the environment is configured correctly before any other logic runs.
Key Takeaway: Python locates modules by iterating through the directories stored in sys.path, so you can resolve import errors by appending your custom directory paths to this list at runtime.