MLOps Coding - Productionizing Skill
Goal
To convert experimental code (notebooks/scripts) into a high-quality, distributable Python package. This skill enforces the src/ layout, a Hybrid Paradigm (OOP structure + Functional purity), and Strict Configuration to ensure scalability, security, and maintainability.
Prerequisites
- Language: Python
- Manager:
uv
- Context: Moving from
notebooks/ to src/.
Instructions
1. Packaging Structure (src Layout)
Adopt the src layout to prevent import errors and separate source from tooling.
Directory Tree:
my-project/
├── pyproject.toml # Dependencies & Metadata
├── uv.lock
├── README.md
└── src/
└── my_package/ # Main package directory
├── __init__.py
├── io/ # Side-effects (Datasets, APIs)
├── domain/ # Pure business logic (Models, Features)
└── application/ # Orchestration (Training loops, Inference)
Configuration: Use pyproject.toml for all build metadata and dependencies.
2. Modularity & Paradigm (Hybrid Style)
Balance structure with predictability.
- Domain Layer (Pure):
- Rule: Code here must be deterministic and free of side effects (no I/O).
- Use Case: Feature transformations, Model architecture definitions.
- Style: Functional (pure functions) or Immutable Objects (dataclasses).
- I/O Layer (Impure):
- Rule: Isolate external interactions here.
- Use Case: Loading data from S3, saving models to disk, logging to MLflow.
- Style: OOP (Classes to manage connections/state).
- Application Layer (Orchestration):
- Rule: Wire Domain and I/O together.
- Use Case: Tuning, Training, Inference, Evaluation, etc.
3. Application Entrypoints
Create standard, installable CLI tools.
Define Script: Create src/my_package/scripts.py with a main() function.
Register: Add to pyproject.toml:
[project.scripts]
my-tool = "my_package.scripts:main"
CLI Execution:
- Dev:
uv run my-tool (No install needed).
- Prod:
pip install . -> my-tool (Installed on PATH).
Guard: Always use if __name__ == "__main__": in scripts to prevent execution on import.
4. Configuration Management
Decouple settings from code using OmegaConf (Parsing) and Pydantic (Validation).
Define Schema (Pydantic):
- Create a class that defines expected types and defaults.
from pydantic import BaseModel
class TrainingConfig(BaseModel):
batch_size: int = 32
learning_rate: float = 0.001
use_gpu: bool = False
Parse & Validate (OmegaConf):
- Load YAML, merge with CLI args, and validate against the schema.
import omegaconf
# 1. Load YAML
conf = omegaconf.OmegaConf.load("config.yaml")
# 2. Merge with CLI (optional)
cli_conf = omegaconf.OmegaConf.from_cli()
merged = omegaconf.OmegaConf.merge(conf, cli_conf)
# 3. Validate -> Returns a validated Pydantic object
cfg: TrainingConfig = TrainingConfig(**omegaconf.OmegaConf.to_container(merged))
Secrets: Use Environment Variables (os.getenv), never commit them.
5. Documentation & Quality
Make code usable and maintainable.
Docstrings: Use Google Style docstrings for all modules, classes, and functions.
def calculate_metric(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Calculates the accuracy score.
Args:
y_true: Ground truth labels.
y_pred: Predicted labels.
Returns:
The accuracy as a float between 0 and 1.
"""
Type Hints: Use standard python typing (typing, list[str]) everywhere.
6. Best Practices Summary
- Config != Code: Never hardcode paths or hyperparams; use the
Pydantic + OmegaConf pattern.
- Entrypoints are APIs: Design your CLI (
[project.scripts]) as the public interface for your automation tools.
- Immutable Core: Keep your domain logic side-effect free; push I/O to the edges.
Self-Correction Checklist
Source: fmind/mlops-python-package — distributed by TomeVault.
1---2name: mlops-industrialization3description: Guide to transform prototypes into robust, distributable Python packages using the src layout, hybrid paradigm, and strict configuration management. Use when this capability is needed.4---56# MLOps Coding - Productionizing Skill78## Goal910To convert experimental code (notebooks/scripts) into a high-quality, distributable Python package. This skill enforces the **src/ layout**, a **Hybrid Paradigm** (OOP structure + Functional purity), and **Strict Configuration** to ensure scalability, security, and maintainability.1112## Prerequisites1314- **Language**: Python15- **Manager**: `uv`16- **Context**: Moving from `notebooks/` to `src/`.1718## Instructions1920### 1. Packaging Structure (`src` Layout)2122Adopt the `src` layout to prevent import errors and separate source from tooling.23241. **Directory Tree**:2526 ```text27 my-project/28 ├── pyproject.toml # Dependencies & Metadata29 ├── uv.lock30 ├── README.md31 └── src/32 └── my_package/ # Main package directory33 ├── __init__.py34 ├── io/ # Side-effects (Datasets, APIs)35 ├── domain/ # Pure business logic (Models, Features)36 └── application/ # Orchestration (Training loops, Inference)37 ```38392. **Configuration**: Use `pyproject.toml` for all build metadata and dependencies.4041### 2. Modularity & Paradigm (Hybrid Style)4243Balance structure with predictability.44451. **Domain Layer (Pure)**:46 - **Rule**: Code here must be deterministic and free of side effects (no I/O).47 - **Use Case**: Feature transformations, Model architecture definitions.48 - **Style**: Functional (pure functions) or Immutable Objects (dataclasses).492. **I/O Layer (Impure)**:50 - **Rule**: Isolate external interactions here.51 - **Use Case**: Loading data from S3, saving models to disk, logging to MLflow.52 - **Style**: OOP (Classes to manage connections/state).533. **Application Layer (Orchestration)**:54 - **Rule**: Wire Domain and I/O together.55 - **Use Case**: Tuning, Training, Inference, Evaluation, etc.5657### 3. Application Entrypoints5859Create standard, installable CLI tools.60611. **Define Script**: Create `src/my_package/scripts.py` with a `main()` function.622. **Register**: Add to `pyproject.toml`:6364 ```toml65 [project.scripts]66 my-tool = "my_package.scripts:main"67 ```68693. **CLI Execution**:70 - **Dev**: `uv run my-tool` (No install needed).71 - **Prod**: `pip install .` -> `my-tool` (Installed on PATH).724. **Guard**: Always use `if __name__ == "__main__":` in scripts to prevent execution on import.7374### 4. Configuration Management7576Decouple settings from code using **OmegaConf** (Parsing) and **Pydantic** (Validation).77781. **Define Schema (Pydantic)**:79 - Create a class that defines *expected* types and defaults.8081 ```python82 from pydantic import BaseModel8384 class TrainingConfig(BaseModel):85 batch_size: int = 3286 learning_rate: float = 0.00187 use_gpu: bool = False88 ```89902. **Parse & Validate (OmegaConf)**:91 - Load YAML, merge with CLI args, and validate against the schema.9293 ```python94 import omegaconf9596 # 1. Load YAML97 conf = omegaconf.OmegaConf.load("config.yaml")98 # 2. Merge with CLI (optional)99 cli_conf = omegaconf.OmegaConf.from_cli()100 merged = omegaconf.OmegaConf.merge(conf, cli_conf)101 # 3. Validate -> Returns a validated Pydantic object102 cfg: TrainingConfig = TrainingConfig(**omegaconf.OmegaConf.to_container(merged))103 ```1041053. **Secrets**: Use Environment Variables (`os.getenv`), never commit them.106107### 5. Documentation & Quality108109Make code usable and maintainable.1101111. **Docstrings**: Use **Google Style** docstrings for all modules, classes, and functions.112113 ```python114 def calculate_metric(y_true: np.ndarray, y_pred: np.ndarray) -> float:115 """Calculates the accuracy score.116117 Args:118 y_true: Ground truth labels.119 y_pred: Predicted labels.120121 Returns:122 The accuracy as a float between 0 and 1.123 """124 ```1251262. **Type Hints**: Use standard python typing (`typing`, `list[str]`) everywhere.127128### 6. Best Practices Summary129130- **Config != Code**: Never hardcode paths or hyperparams; use the `Pydantic + OmegaConf` pattern.131- **Entrypoints are APIs**: Design your CLI (`[project.scripts]`) as the public interface for your automation tools.132- **Immutable Core**: Keep your domain logic side-effect free; push I/O to the edges.133134## Self-Correction Checklist135136- [ ] **No Side Effects on Import**: Does `import my_package` run any code? (It shouldn't).137- [ ] **Src Layout**: Is code inside `src/`?138- [ ] **Config Safety**: Are secrets excluded from `pyproject.toml` and YAML?139- [ ] **Typing**: Are function signatures fully type-hinted?140- [ ] **Entrypoints**: Is the CLI registered in `pyproject.toml`?141142---143> Source: [fmind/mlops-python-package](https://github.com/fmind/mlops-python-package) — distributed by [TomeVault](https://tomevault.io).144<!-- tomevault:4.0:skill_md:2026-06-25 -->