### Simplified Root Setup Source: https://github.com/ashleve/rootutils/blob/main/README.md Combines finding the root and setting up the environment (except changing the current working directory) into a single function call. ```python import rootutils root = rootutils.setup_root(__file__, dotenv=True, pythonpath=True, cwd=False) ``` -------------------------------- ### Install Autoroot Source: https://github.com/ashleve/rootutils/blob/main/README.md Install the experimental 'autoroot' and 'autorootcwd' packages for automatic root setup upon import. ```bash pip install autoroot autorootcwd ``` -------------------------------- ### Autoroot Setup (PYTHONPATH, Env Vars) Source: https://github.com/ashleve/rootutils/blob/main/README.md Importing 'autoroot' automatically sets up the project root by adding it to PYTHONPATH and loading environment variables from .env. ```python import autoroot # root setup, do not delete ``` -------------------------------- ### Install rootutils Source: https://github.com/ashleve/rootutils/blob/main/README.md Install the rootutils package using pip. ```bash pip install rootutils ``` -------------------------------- ### One-liner Setup with setup_root Source: https://context7.com/ashleve/rootutils/llms.txt Combines finding the project root and setting up the runtime environment in a single call. Returns the resolved root path. Useful for ML/data projects to enable absolute imports and load environment variables. ```python import rootutils # Minimal usage — only load .env and set PROJECT_ROOT (defaults) root = rootutils.setup_root(__file__) # Recommended configuration for ML/data projects root = rootutils.setup_root( search_from=__file__, indicator=[ ".project-root", ".git"], project_root_env_var=True, dotenv=True, # load secrets from root/.env pythonpath=True, # enable `from src.models import ...` style imports cwd=False, # keep original working directory ) # Now absolute imports relative to project root work anywhere from src.models.resnet import ResNet # noqa: E402 from src.data.datamodule import MyDataModule # noqa: E402 import os print(os.environ.get("PROJECT_ROOT")) # /home/user/my_project print(root / "data" / "raw") # /home/user/my_project/data/raw # Inside a Jupyter notebook nested at notebooks/experiments/run.ipynb root = rootutils.setup_root(__file__, dotenv=True, pythonpath=True, cwd=True) ``` -------------------------------- ### Autoroot Setup (Change CWD) Source: https://github.com/ashleve/rootutils/blob/main/README.md Importing 'autorootcwd' automatically sets up the project root and changes the current working directory to the root. ```python import autorootcwd # root setup, do not delete ``` -------------------------------- ### Find Project Root Directory Source: https://github.com/ashleve/rootutils/blob/main/README.md Find the absolute root path by searching for a specific indicator file. The search starts from the current file and recursively checks parent directories. Returns a pathlib object. ```python import rootutils # find absolute root path (searches for directory containing .project-root file) # search starts from current file and recursively goes over parent directories # returns pathlib object path = rootutils.find_root(search_from=__file__, indicator=".project-root") ``` ```python # find absolute root path (searches for directory containing any of the files on the list) path = rootutils.find_root(search_from=__file__, indicator=[".git", "setup.cfg"]) ``` -------------------------------- ### Set Project Root and Environment Source: https://github.com/ashleve/rootutils/blob/main/README.md Configure the project root by setting environment variables, loading .env files, adding to PYTHONPATH, and changing the current working directory. ```python # take advantage of the pathlib syntax data_dir = path / "data" assert data_dir.exists(), f"path doesn't exist: {data_dir}" ``` ```python # set root directory rootutils.set_root( path=path # path to the root directory project_root_env_var=True, # set the PROJECT_ROOT environment variable to root directory dotenv=True, # load environment variables from .env if exists in root directory pythonpath=True, # add root directory to the PYTHONPATH (helps with imports) cwd=True, # change current working directory to the root directory (helps with filepaths) ) ``` -------------------------------- ### setup_root Source: https://context7.com/ashleve/rootutils/llms.txt A convenience function that combines `find_root` and `set_root` into a single call. It finds the project root and applies the specified environment side-effects, returning the resolved root path. ```APIDOC ## setup_root ### Description The most commonly used entry-point. Finds the project root starting from `search_from` using the specified indicators, then immediately applies all requested environment side-effects. Returns the resolved root `Path`. ### Parameters - **search_from** (str | Path | None): The directory to start searching from. Defaults to the directory of the calling file. - **indicator** (str | list[str] | None): A file name or a list of file names to search for. Defaults to a standard set of project root indicators. - **project_root_env_var** (bool): If True, sets the `PROJECT_ROOT` environment variable to the provided path. - **dotenv** (bool): If True, loads environment variables from a `.env` file in the root directory. - **pythonpath** (bool): If True, prepends the root directory to `sys.path`. - **cwd** (bool): If True, changes the current working directory to the root directory. ### Returns - Path: The resolved project root directory. ### Example ```python import rootutils import os # Minimal usage — only load .env and set PROJECT_ROOT (defaults) root = rootutils.setup_root(__file__) # Recommended configuration for ML/data projects root = rootutils.setup_root( search_from=__file__, indicator=[ ".project-root", ".git" ], project_root_env_var=True, dotenv=True, # load secrets from root/.env pythonpath=True, # enable `from src.models import ...` style imports cwd=False, # keep original working directory ) # Now absolute imports relative to project root work anywhere # from src.models.resnet import ResNet # noqa: E402 # from src.data.datamodule import MyDataModule # noqa: E402 print(os.environ.get("PROJECT_ROOT")) # /home/user/my_project print(root / "data" / "raw") # /home/user/my_project/data/raw # Inside a Jupyter notebook nested at notebooks/experiments/run.ipynb root = rootutils.setup_root(__file__, dotenv=True, pythonpath=True, cwd=True) ``` ``` -------------------------------- ### Configure Runtime Environment with set_root Source: https://context7.com/ashleve/rootutils/llms.txt Configures the runtime environment using a known root path. Options include setting PROJECT_ROOT environment variable, loading .env files, prepending to sys.path, and changing the current working directory. Raises FileNotFoundError if the path does not exist. ```python import rootutils root = rootutils.find_root(search_from=__file__) # Full configuration — all options shown explicitly rootutils.set_root( path=root, project_root_env_var=True, # os.environ["PROJECT_ROOT"] = str(root) dotenv=True, # load root/.env via python-dotenv pythonpath=True, # sys.path.insert(0, str(root)) cwd=True, # os.chdir(root) ) import os, sys print(os.environ["PROJECT_ROOT"]) print(sys.path[0]) print(os.getcwd()) # Minimal — only set PROJECT_ROOT, do not touch path or cwd rootutils.set_root(root, project_root_env_var=True, dotenv=False, pythonpath=False, cwd=False) # Error: path must exist try: rootutils.set_root("/nonexistent/path") except FileNotFoundError as e: print(f"Error: {e}") ``` -------------------------------- ### Use autosetup to automatically infer root path Source: https://context7.com/ashleve/rootutils/llms.txt Use this convenience function to automatically infer the project root. It falls back to os.getcwd() when running inside a Jupyter kernel or pytest. ```python import rootutils # Equivalent to setup_root(__file__, ...) but infers search path automatically root = rootutils.autosetup() ``` ```python import rootutils # Custom indicator and options root = rootutils.autosetup( indicator=".project-root", project_root_env_var=True, dotenv=True, pythonpath=True, cwd=False, ) import os print(root) # PosixPath('/home/user/my_project') print(os.environ["PROJECT_ROOT"]) ``` ```python # In a notebook cell (ipykernel is detected, falls back to os.getcwd()) root = rootutils.autosetup(dotenv=True, pythonpath=True, cwd=True) ``` -------------------------------- ### Default Root Indicators Source: https://github.com/ashleve/rootutils/blob/main/README.md Lists the default files rootutils searches for to identify the project root directory when no specific indicator is provided. ```python [".project-root", "setup.cfg", "setup.py", ".git", "pyproject.toml"] ``` -------------------------------- ### set_root Source: https://context7.com/ashleve/rootutils/llms.txt Configures the runtime environment for a known root path by applying side-effects like setting the PROJECT_ROOT environment variable, loading .env files, prepending to sys.path, and changing the working directory. ```APIDOC ## set_root ### Description Accepts an already-resolved root `Path` (or string) and applies any combination of four side-effects: sets the `PROJECT_ROOT` environment variable, loads `.env` from the root, prepends the root to `sys.path` (PYTHONPATH), and changes the process working directory to root. ### Parameters - **path** (str | Path): The path to the project root. - **project_root_env_var** (bool): If True, sets the `PROJECT_ROOT` environment variable to the provided path. - **dotenv** (bool): If True, loads environment variables from a `.env` file in the root directory. - **pythonpath** (bool): If True, prepends the root directory to `sys.path`. - **cwd** (bool): If True, changes the current working directory to the root directory. ### Returns None ### Raises - FileNotFoundError: If the provided `path` does not exist. ### Example ```python import rootutils import os import sys root = rootutils.find_root(search_from=__file__) # Full configuration — all options shown explicitly rootutils.set_root( path=root, project_root_env_var=True, # os.environ["PROJECT_ROOT"] = str(root) dotenv=True, # load root/.env via python-dotenv pythonpath=True, # sys.path.insert(0, str(root)) cwd=True, # os.chdir(root) ) print(os.environ["PROJECT_ROOT"]) print(sys.path[0]) print(os.getcwd()) # Minimal — only set PROJECT_ROOT, do not touch path or cwd rootutils.set_root(root, project_root_env_var=True, dotenv=False, pythonpath=False, cwd=False) # Error: path must exist try: rootutils.set_root("/nonexistent/path") except FileNotFoundError as e: print(f"Error: {e}") ``` ``` -------------------------------- ### Find Project Root Directory with rootutils Source: https://context7.com/ashleve/rootutils/llms.txt Locates the project root by searching for indicator files. Supports default or custom indicators and various search path inputs. Raises FileNotFoundError or TypeError on failure. ```python import rootutils from pathlib import Path # Locate root using the default set of indicators: # [".project-root", "setup.cfg", "setup.py", ".git", "pyproject.toml"] root = rootutils.find_root(search_from=__file__) print(root) # e.g. PosixPath('/home/user/my_project') # Use a single custom indicator root = rootutils.find_root(search_from=__file__, indicator=".project-root") # Use a list of custom indicators — first match wins root = rootutils.find_root( search_from=__file__, indicator=[ ".git", "setup.cfg", "pyproject.toml"], ) # Works with strings, Path objects, or the bare "." / "" sentinel root = rootutils.find_root(search_from=Path(__file__)) root = rootutils.find_root(search_from=".") # Build paths relative to root using pathlib data_dir = root / "data" cfg_file = root / "configs" / "train.yaml" assert data_dir.exists(), f"Missing data directory: {data_dir}" # Error cases try: rootutils.find_root(__file__, indicator="nonexistent_marker") except FileNotFoundError as e: print(f"Root not found: {e}") try: rootutils.find_root([]) # wrong type for search_from except TypeError as e: print(f"Type error: {e}") ``` -------------------------------- ### find_root Source: https://context7.com/ashleve/rootutils/llms.txt Locates the project root directory by recursively searching upward for specified indicator files. It can raise FileNotFoundError or TypeError for invalid arguments or if the root is not found. ```APIDOC ## find_root ### Description Recursively walks up the directory tree from `search_from`, returning the first ancestor directory that contains at least one of the specified `indicator` files. Raises `FileNotFoundError` if no matching directory is found and `TypeError` if arguments have incorrect types. ### Parameters - **search_from** (str | Path | None): The directory to start searching from. Defaults to the directory of the calling file. - **indicator** (str | list[str] | None): A file name or a list of file names to search for. Defaults to a standard set of project root indicators. ### Returns - Path: The resolved project root directory. ### Raises - FileNotFoundError: If no directory containing any of the indicator files is found. - TypeError: If `search_from` or `indicator` have incorrect types. ### Example ```python import rootutils from pathlib import Path # Locate root using the default set of indicators root = rootutils.find_root(search_from=__file__) print(root) # Use a single custom indicator root = rootutils.find_root(search_from=__file__, indicator=".project-root") # Use a list of custom indicators root = rootutils.find_root( search_from=__file__, indicator=[ ".git", "setup.cfg", "pyproject.toml" ], ) # Works with strings, Path objects, or the bare "." / "" sentinel root = rootutils.find_root(search_from=Path(__file__)) root = rootutils.find_root(search_from=".") # Build paths relative to root using pathlib data_dir = root / "data" cfg_file = root / "configs" / "train.yaml" assert data_dir.exists(), f"Missing data directory: {data_dir}" # Error cases try: rootutils.find_root(__file__, indicator="nonexistent_marker") except FileNotFoundError as e: print(f"Root not found: {e}") try: rootutils.find_root([]) # wrong type for search_from except TypeError as e: print(f"Type error: {e}") ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.