rootutils

1.0.7 · active · verified Tue Apr 14

rootutils (formerly pyrootutils) is a Python library designed for simple and robust project root setup. It helps locate the project root directory using an indicator file and can optionally add it to `sys.path` for simplified imports. The library is currently at version 1.0.7 and maintains a moderately active release cadence, typically releasing minor updates or bug fixes every few months.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `rootutils.autosetup()` to find the project root (indicated by `.project-root`) and add it to `sys.path`. This enables direct imports of modules located within the project root, simplifying project structure management. The example simulates a project root by creating a temporary indicator file.

import rootutils
import os
import sys

# Simulate a project root by creating an indicator file in the current directory.
# In a real project, you would call this from a subdirectory.
indicator_file = ".project-root"
with open(indicator_file, "w") as f:
    f.write("")

try:
    # Find the project root (current directory in this simulation)
    # and add it to sys.path for simplified imports.
    root_dir = rootutils.autosetup(
        indicator_file=indicator_file, # The file to look for
        project_dir=os.getcwd(),     # Start search from current directory
        add_to_pythonpath=True       # Explicitly ensure it's added
    )

    print(f"Project root found: {root_dir}")
    print(f"Does sys.path contain project root? {str(root_dir) in sys.path}")

    # Example: In a real project, if you have a 'config' directory at the root,
    # you could now do: 'from config import settings'
    # without complex relative imports.

finally:
    # Clean up the simulated indicator file
    if os.path.exists(indicator_file):
        os.remove(indicator_file)

view raw JSON →