To import functions from another folder in Python, the most reliable method is to add the target folder's path to sys.path using the sys module or by structuring your project as a package with __init__.py files. This allows the Python interpreter to locate the module regardless of where the script is executed from.

What You'll Need

  • Python installed on your system (Version 3.x is recommended).
  • A code editor or IDE (such as VS Code, PyCharm, or Sublime Text).
  • A basic project directory containing at least two folders: one for your main script and one for the functions you wish to import.

Step-by-Step

  1. Organize Your Directory Structure: Create a clear folder hierarchy. For this example, assume a project root folder named my_project. Inside it, create a folder named utilities (where your functions live) and a separate folder or root area for your main.py script. Your structure should look like this:
    my_project/
    ├── main.py
    └── utilities/
    └── helper.py
  2. Create the Function Module: Open helper.py inside the utilities folder and define the functions you want to share. For example:
    def greet(name):
    return f"Hello, {name}! Welcome to the project."

    Save this file.
  3. Add an Init File (Optional but Recommended): To tell Python that the utilities folder should be treated as a package, create an empty file named __init__.py inside the utilities folder. While Python 3.3+ supports implicit namespace packages without this file, adding it ensures compatibility across different environments and tools.
  4. Modify the System Path in the Main Script: In main.py, you must tell Python where to look for the utilities folder because it is not in the default search path. Use the sys module to append the directory path:
    import sys
    import os

    # Get the absolute path to the directory containing the utilities folder
    current_dir = os.path.dirname(os.path.abspath(__file__))
    utilities_path = os.path.join(current_dir, 'utilities')
    sys.path.append(utilities_path)

    Using os.path.abspath ensures that the script works regardless of which directory you are in when you run the command in the terminal.
  5. Import the Specific Function: Now that the folder is in the system path, you can import the function directly from the module:
    from helper import greet

    print(greet("Developer"))
  6. Run the Script: Execute your script from the terminal using python main.py. Python will now look into the utilities folder, find helper.py, and execute the greet function.

Common Mistakes

One of the most frequent errors is using relative imports (e.g., from ..utilities import helper) in a script that is being run as the main entry point. Relative imports only work within packages that are imported by other modules; they fail with a ImportError: attempted relative import with no known parent package when you run the file directly. Always use absolute paths or sys.path modifications for your primary execution script.

Another common mistake is naming your folders or files after built-in Python libraries. For example, if you name your folder json or random, Python may attempt to import your local folder instead of the standard library, leading to confusing AttributeError messages when you try to use actual JSON or random functions.

Users often forget that sys.path.append() only lasts for the duration of the script's execution. If you restart the program or run a different script, you must include the path modification logic again. This leads some developers to believe the folder was "permanently" added to Python, which is not the case unless you modify the PYTHONPATH environment variable at the OS level.

Tips

For larger projects, instead of manually appending paths in every file, consider creating a setup.py file and installing your project in "editable mode" using pip install -e .. This registers your project folder in the Python site-packages directory, allowing you to use import utilities.helper from anywhere on your system without needing sys.path hacks.

If you have multiple folders of utilities, create a single src or lib folder to hold them all. You only need to add the src folder to sys.path once, and then you can import from any subfolder within it using the dot notation: from src.utilities import helper and from src.database import connection.

Always use absolute paths when modifying sys.path. Using a simple string like sys.path.append('utilities') relies on the Current Working Directory (CWD). If you run your script from a different folder in the terminal, the CWD changes, and Python will fail to find the folder. Using os.path.abspath(__file__) anchors the search to the location of the script itself.

Troubleshooting

If you receive a ModuleNotFoundError, the first step is to print the current system path to see where Python is actually looking. Add print(sys.path) immediately after your sys.path.append() line. Check if the full, absolute path to your utilities folder appears in the resulting list. If it does not, your path concatenation logic is likely incorrect.

If the path is correct but the import still fails, verify the file name and the function name. Python is case-sensitive; importing Helper when the file is named helper.py will result in an error. Also, ensure there are no hidden characters or typos in the filename, such as helper.py.txt (which happens often on Windows if file extensions are hidden).

Check for circular imports. This happens when main.py imports helper.py, and helper.py simultaneously tries to import something from main.py. This creates a loop that confuses the interpreter. To fix this, move the shared logic into a third, independent module that both files can import without depending on each other.

If you are using an IDE like PyCharm, the editor might show a red underline (warning) even if the code runs perfectly. This is because the IDE's static analyzer doesn't execute the sys.path.append() code. To fix this, right-click the folder in the project sidebar and select Mark Directory as > Sources Root. This tells the IDE to include that folder in its internal search path for autocomplete and linting.

Frequently Asked Questions

Can I import functions from a folder outside my project root?

Yes. You can provide any absolute path to sys.path.append(), such as sys.path.append('/Users/name/external_libs'). Python will look in that specific directory on your hard drive for the module.

What is the difference between import module and from module import function?

import module imports the entire file; you must call functions using module.function(). from module import function brings the specific function into your current namespace, allowing you to call function() directly.

Do I really need __init__.py in Python 3?

Technically, no. Python 3.3+ supports "Implicit Namespace Packages." However, including an empty __init__.py is still a best practice to explicitly mark a directory as a Python package for other developers and tools.

Will this work on both Windows and macOS/Linux?

Yes, provided you use os.path.join() instead of hardcoding slashes. Windows uses backslashes (\) and Unix-based systems use forward slashes (/). The os module handles these differences automatically.

Is modifying sys.path considered bad practice?

For small scripts or quick prototypes, it is perfectly acceptable. For professional, distributable software, it is better to use a proper package structure with a pyproject.toml or setup.py file and install the package via pip.