Model registry version mock in Python
A simple in-memory model registry that stores model versions with metadata and supports version listing and latest retrieval.
Python code
32 linesclass ModelRegistry:
def __init__(self):
self.models = {}
def register(self, name, version, model_type, metrics=None):
if name not in self.models:
self.models[name] = []
entry = {
"version": version,
"model_type": model_type,
"metrics": metrics or {}
}
self.models[name].append(entry)
return f"Registered {model_type} '{name}' version {version}"
def get_latest(self, name):
if name not in self.models or not self.models[name]:
return None
return self.models[name][-1]
def list_versions(self, name):
if name not in self.models:
return []
return [entry["version"] for entry in self.models[name]]
if __name__ == "__main__":
registry = ModelRegistry()
print(registry.register("sentiment-model", "1.0.0", "LogisticRegression", {"accuracy": 0.87}))
print(registry.register("sentiment-model", "1.1.0", "RandomForest", {"accuracy": 0.91}))
print("Versions:", registry.list_versions("sentiment-model"))
print("Latest:", registry.get_latest("sentiment-model"))
Output
Registered LogisticRegression 'sentiment-model' version 1.0.0
Registered RandomForest 'sentiment-model' version 1.1.0
Versions: ['1.0.0', '1.1.0']
Latest: {'version': '1.1.0', 'model_type': 'RandomForest', 'metrics': {'accuracy': 0.91}}
How it works
The register method stores each model version as a new dict entry in a list keyed by model name. Using a list preserves insertion order, so the last appended version is treated as the latest. The get_latest method returns the final element of the list, while list_versions extracts just the version strings. Metrics default to an empty dict when not provided, keeping the data structure consistent.
Common mistakes
- Forgetting to initialize the models list for a new model name before appending
- Assuming versions arrive in chronological order instead of relying on insertion order
- Returning the full entry instead of just the version string from `get_latest`
Variations
- Use a dict keyed by (name, version) tuple for direct version lookups instead of a list
- Add a semantic version comparison to `get_latest` so versions are sorted numerically rather than by insertion
Real-world use cases
- Prototyping an ML experiment tracker before integrating with a full platform like MLflow.
- Unit-testing model-serving code that needs a lightweight registry stub.
- Managing rolling model deployments across environments in a CI/CD pipeline.
Sponsored
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.