Monorepo Path Management Library
The `monorepo` Python library (version 0.2.0) simplifies importing packages and modules from the root of a monorepo structure. It achieves this by programmatically adding the monorepo root to `sys.path`, allowing sub-packages to reference each other easily without complex relative imports. The library has an active release cadence, with the latest release in early 2024.
Common errors
-
ModuleNotFoundError: No module named 'my_monorepo_package'
cause `monorepo.setup()` was not called, or the `root` path was configured incorrectly, preventing Python from finding modules in your monorepo.fixEnsure `Monorepo.setup(root=...)` is called early in your application's lifecycle, typically in `__init__.py` or the main entry point, and that the `root` argument correctly points to the absolute path of your monorepo's top-level directory. -
TypeError: Monorepo.setup() missing 1 required keyword-only argument: 'root'
cause The `root` argument was omitted when calling `Monorepo.setup()`, which is a mandatory parameter.fixProvide the `root` argument with the absolute path to your monorepo's root directory, e.g., `Monorepo.setup(root=Path(__file__).parent.parent.parent)`.
Warnings
- gotcha Incorrect `root` path specified for `Monorepo.setup()`.
- gotcha Conflicts with existing `PYTHONPATH` environment variable or other programmatic `sys.path` modifications.
- gotcha IDE/Linter issues with recognizing monorepo paths.
Install
-
pip install monorepo
Imports
- Monorepo
from monorepo import Monorepo
Quickstart
from pathlib import Path
from monorepo import Monorepo
import sys
# Simulate a monorepo structure for demonstration
# In a real monorepo, __file__ would be inside a sub-package
# For this example, let's create a dummy structure
# Create a dummy monorepo root and a sub-package
monorepo_root = Path('./my_monorepo_root')
monorepo_root.mkdir(exist_ok=True)
(monorepo_root / 'service_a').mkdir(exist_ok=True)
(monorepo_root / 'service_b').mkdir(exist_ok=True)
# Create a dummy module in service_b
(monorepo_root / 'service_b' / '__init__.py').touch(exist_ok=True)
(monorepo_root / 'service_b' / 'my_module.py').write_text("MY_VALUE = 'Hello from service_b!'")
# Now, simulate being inside 'service_a/main.py'
# The 'root' should point to 'my_monorepo_root'
Monorepo.setup(root=monorepo_root.absolute())
# Now you can import from other services/packages in the monorepo root
# This would typically be 'from service_b import my_module'
# We need to ensure 'service_b' is discoverable, which Monorepo.setup does.
# If running from a different directory, adjust sys.path for the quickstart
try:
from service_b import my_module
print(f"Successfully imported my_module: {my_module.MY_VALUE}")
except ModuleNotFoundError as e:
print(f"Failed to import module: {e}")
finally:
# Clean up dummy files
import shutil
if monorepo_root.exists():
shutil.rmtree(monorepo_root)