pythonintermediate

Abstract Base Classes with abc

Define interfaces and enforce method implementation with Python's abc module.

python
from abc import ABC, abstractmethod
from typing import List

class Repository(ABC):
    @abstractmethod
    def find_by_id(self, id: str) -> dict:
        ...

    @abstractmethod
    def save(self, entity: dict) -> None:
        ...

    @abstractmethod
    def delete(self, id: str) -> bool:
        ...

    def find_all(self) -> List[dict]:
        """Optional: concrete default implementation."""
        return []

class InMemoryRepo(Repository):
    def __init__(self):
        self._data = {}

    def find_by_id(self, id: str) -> dict:
        return self._data.get(id)

    def save(self, entity: dict) -> None:
        self._data[entity["id"]] = entity

    def delete(self, id: str) -> bool:
        return self._data.pop(id, None) is not None

repo = InMemoryRepo()
repo.save({"id": "1", "name": "Alice"})
print(repo.find_by_id("1"))

Use Cases

  • Interface contracts
  • Plugin systems
  • Dependency injection

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.