Skip to content

Custom File Handlers

OptiScope allows you to add support for custom file formats by implementing a FormatHandler.

Implementing a Handler

To create a new handler, subclass BaseFormatHandler (or StructuredFormatHandler/TabularFormatHandler) and implement the required methods.

from pathlib import Path
from typing import Any
from optiscope.io.base import BaseFormatHandler
from optiscope.core.data_model import OptimizationResult

class MyCustomHandler(BaseFormatHandler):
    format_name = "MyCustomFormat"
    file_extensions = [".myfmt"]

    @classmethod
    def can_handle(cls, filepath: Path) -> bool:
        return filepath.suffix == ".myfmt"

    def read(self, filepath: Path, **kwargs: Any) -> OptimizationResult:
        # Implement reading logic here
        # ...
        return OptimizationResult(...)

    def write(self, result: OptimizationResult, filepath: Path, **kwargs: Any) -> None:
        # Implement writing logic here
        pass

Registering the Handler

Once implemented, you need to register your handler with the global registry.

from optiscope.io.registry import get_global_registry

# Register the handler
registry = get_global_registry()
registry.register(MyCustomHandler)

# Now you can use it seamlessly
from optiscope.io.registry import load_results

results = load_results("data.myfmt")

Using Entry Points

You can also register handlers via Python entry points in your pyproject.toml or setup.py.

[project.entry-points."optiscope.io.handlers"]
my_handler = "my_package.handlers:MyCustomHandler"