pythonintermediate
Abstract Base Classes with abc
Define interfaces and enforce method implementation with Python's abc module.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonadvanced
Abc Abstract
Advanced Python pattern: abc-abstract
Best for: advanced programming
#python#advanced
pythonadvanced
Abc Registry
Advanced Python pattern: abc-registry
Best for: advanced programming
#python#advanced
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management