Claude Code for abc: Abstract Base Classes in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for abc: Abstract Base Classes in Python
AI

Claude Code for abc: Abstract Base Classes in Python

Published: July 8, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s abc module provides Abstract Base Classes (ABCs) for defining interfaces that subclasses must implement. from abc import ABC, abstractmethod, ABCMeta. ABC: class Base(ABC): @abstractmethod def fn(self) -> int: .... Instantiating a class with unimplemented abstract methods raises TypeError. ABCMeta: class Base(metaclass=ABCMeta): ... — equivalent to class Base(ABC). abstractmethod: @abstractmethod def method(self) -> T: ... — must be overridden. abstractclassmethod: use @classmethod @abstractmethod (3.3+). abstractstaticmethod: use @staticmethod @abstractmethod. abstractproperty: use @property @abstractmethod. register: Base.register(ExternalClass) — mark without inheritance. subclasshook: @classmethod def __subclasshook__(cls, C): return True if hasattr(C,"method") else NotImplemented. isinstance/issubclass: work with registered virtual subclasses. abstractmethods: Base.__abstractmethods__ — frozenset of unimplemented names. get_cache_token: abc.get_cache_token() — for invalidating subclass check caches. Mixin: class LogMixin(ABC): def log(self): ... — concrete helpers in abstract base. Template method: concrete base method calls @abstractmethod hooks. Multiple inheritance: class C(Mixin1, Mixin2, ABC): .... Claude Code generates storage backends, serializer interfaces, plugin registries, and strategy patterns.

CLAUDE.md for abc

## abc Stack
- Stdlib: from abc import ABC, abstractmethod, ABCMeta
- Interface: class IStorage(ABC): @abstractmethod def read/write/delete/exists
- Partial: concrete helpers in ABC + @abstractmethod for primitive operations
- Template: concrete method in base calls @abstractmethod hook methods
- Register: ABC.register(ThirdPartyClass) — virtual subclass without inheritance
- Check: isinstance(obj, IStorage) works for both real and registered subclasses

abc Interface and Mixin Pipeline

# app/interfaces.py — ABC, abstractmethod, register, mixins, template method, plugin
from __future__ import annotations

import hashlib
import io
import logging
from abc import ABC, ABCMeta, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Any, BinaryIO, Iterator, Sequence

log = logging.getLogger(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# 1. Storage backend interface
# ─────────────────────────────────────────────────────────────────────────────

class IStorage(ABC):
    """
    Abstract storage backend. Concrete implementations provide read, write,
    delete, exists; this class adds list_keys() and get_or_default() for free.

    Example:
        class LocalStorage(IStorage):
            def __init__(self, base: Path): self.base = base
            def read(self, key):   return (self.base/key).read_bytes()
            def write(self, key, data): (self.base/key).write_bytes(data)
            def delete(self, key): (self.base/key).unlink(missing_ok=True)
            def exists(self, key): return (self.base/key).exists()
            def keys(self):        return [p.name for p in self.base.iterdir()]
    """

    @abstractmethod
    def read(self, key: str) -> bytes:
        """Read and return raw bytes for key."""
        ...

    @abstractmethod
    def write(self, key: str, data: bytes) -> None:
        """Write bytes under key."""
        ...

    @abstractmethod
    def delete(self, key: str) -> None:
        """Delete key; no-op if not found."""
        ...

    @abstractmethod
    def exists(self, key: str) -> bool:
        """Return True if key exists."""
        ...

    @abstractmethod
    def keys(self) -> list[str]:
        """Return all stored keys."""
        ...

    # ── Concrete helpers built on the abstract primitives ──

    def get_or_default(self, key: str, default: bytes = b"") -> bytes:
        """Read key or return default if not found."""
        return self.read(key) if self.exists(key) else default

    def copy(self, src: str, dst: str) -> None:
        """Copy src to dst within this storage."""
        self.write(dst, self.read(src))

    def checksum(self, key: str) -> str:
        """SHA-256 checksum of stored bytes."""
        return hashlib.sha256(self.read(key)).hexdigest()


class MemoryStorage(IStorage):
    """
    In-memory storage backend — useful for tests.

    Example:
        store = MemoryStorage()
        store.write("key", b"data")
        assert store.exists("key")
        assert store.read("key") == b"data"
    """

    def __init__(self) -> None:
        self._data: dict[str, bytes] = {}

    def read(self, key: str) -> bytes:
        if key not in self._data:
            raise KeyError(key)
        return self._data[key]

    def write(self, key: str, data: bytes) -> None:
        self._data[key] = data

    def delete(self, key: str) -> None:
        self._data.pop(key, None)

    def exists(self, key: str) -> bool:
        return key in self._data

    def keys(self) -> list[str]:
        return list(self._data.keys())


class LocalStorage(IStorage):
    """
    Filesystem-backed storage backend.

    Example:
        store = LocalStorage(Path("/tmp/store"))
        store.write("cfg.json", b'{"k":1}')
        print(store.keys())
    """

    def __init__(self, base: str | Path) -> None:
        self.base = Path(base)
        self.base.mkdir(parents=True, exist_ok=True)

    def read(self, key: str) -> bytes:
        return (self.base / key).read_bytes()

    def write(self, key: str, data: bytes) -> None:
        p = self.base / key
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_bytes(data)

    def delete(self, key: str) -> None:
        (self.base / key).unlink(missing_ok=True)

    def exists(self, key: str) -> bool:
        return (self.base / key).exists()

    def keys(self) -> list[str]:
        return [p.name for p in self.base.iterdir() if p.is_file()]


# ─────────────────────────────────────────────────────────────────────────────
# 2. Serializer interface (abstract property + methods)
# ─────────────────────────────────────────────────────────────────────────────

class ISerializer(ABC):
    """
    Abstract serializer with abstract content_type property.

    Example:
        class JsonSerializer(ISerializer):
            @property
            def content_type(self): return "application/json"
            def encode(self, obj):  return json.dumps(obj).encode()
            def decode(self, data): return json.loads(data)
    """

    @property
    @abstractmethod
    def content_type(self) -> str:
        """MIME type for this format."""
        ...

    @abstractmethod
    def encode(self, obj: Any) -> bytes:
        """Serialize obj to bytes."""
        ...

    @abstractmethod
    def decode(self, data: bytes) -> Any:
        """Deserialize bytes back to a Python object."""
        ...

    def roundtrip(self, obj: Any) -> Any:
        """Encode then decode — useful for testing."""
        return self.decode(self.encode(obj))


import json as _json  # noqa: E402


class JsonSerializer(ISerializer):
    @property
    def content_type(self) -> str:
        return "application/json"

    def encode(self, obj: Any) -> bytes:
        return _json.dumps(obj, default=str).encode()

    def decode(self, data: bytes) -> Any:
        return _json.loads(data)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Template method pattern
# ─────────────────────────────────────────────────────────────────────────────

class DataPipeline(ABC):
    """
    Template method: run() calls extract → transform → load in order.
    Subclasses implement extract and transform; load has a default.

    Example:
        class CSVPipeline(DataPipeline):
            def extract(self): return list(csv.DictReader(open("data.csv")))
            def transform(self, data): return [clean(r) for r in data]
    """

    def run(self) -> int:
        """Execute the full pipeline; return number of records loaded."""
        log.info("%s: extracting", self.__class__.__name__)
        raw  = self.extract()

        log.info("%s: transforming %d records", self.__class__.__name__, len(raw))
        data = self.transform(raw)

        log.info("%s: loading %d records", self.__class__.__name__, len(data))
        self.load(data)
        return len(data)

    @abstractmethod
    def extract(self) -> list[dict]:
        """Extract raw records from the source."""
        ...

    @abstractmethod
    def transform(self, data: list[dict]) -> list[dict]:
        """Clean and transform records."""
        ...

    def load(self, data: list[dict]) -> None:
        """Load into destination — default: print to stdout."""
        for record in data:
            print(_json.dumps(record))


class EchoDataPipeline(DataPipeline):
    """Concrete pipeline that just echos provided data."""

    def __init__(self, records: list[dict]) -> None:
        self._records = records

    def extract(self) -> list[dict]:
        return list(self._records)

    def transform(self, data: list[dict]) -> list[dict]:
        return [{k: str(v).strip() for k, v in r.items()} for r in data]


# ─────────────────────────────────────────────────────────────────────────────
# 4. Mixin ABC pattern
# ─────────────────────────────────────────────────────────────────────────────

class ReprMixin(ABC):
    """
    Mixin: auto-generate __repr__ from dataclass-like fields.
    Concrete classes define _repr_fields as a tuple of attribute names.
    """

    @property
    @abstractmethod
    def _repr_fields(self) -> tuple[str, ...]:
        ...

    def __repr__(self) -> str:
        attrs = ", ".join(
            f"{k}={getattr(self, k, '?')!r}" for k in self._repr_fields
        )
        return f"{self.__class__.__name__}({attrs})"


class EqMixin(ABC):
    """Mixin: equality based on _eq_fields."""

    @property
    @abstractmethod
    def _eq_fields(self) -> tuple[str, ...]:
        ...

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, self.__class__):
            return NotImplemented
        return all(
            getattr(self, k) == getattr(other, k)
            for k in self._eq_fields
        )

    def __hash__(self) -> int:
        return hash(tuple(getattr(self, k) for k in self._eq_fields))


class Entity(ReprMixin, EqMixin, ABC):
    """Base entity combining repr and equality mixins."""

    @property
    def _repr_fields(self) -> tuple[str, ...]:
        return self._eq_fields


# ─────────────────────────────────────────────────────────────────────────────
# 5. Plugin registry via register()
# ─────────────────────────────────────────────────────────────────────────────

class Converter(ABC):
    """
    Abstract converter with virtual-subclass registration.
    Third-party classes can be registered without inheriting.

    Example:
        Converter.register(ThirdPartyConverter)
        isinstance(ThirdPartyConverter(), Converter)  # True
    """
    _registry: dict[str, type[Converter]] = {}

    @abstractmethod
    def convert(self, value: Any) -> Any: ...

    @classmethod
    def register_named(cls, name: str):
        """
        Class decorator to register a converter under a name.

        Example:
            @Converter.register_named("int")
            class IntConverter(Converter):
                def convert(self, value): return int(value)
        """
        def decorator(klass):
            cls._registry[name] = klass
            return klass
        return decorator

    @classmethod
    def get(cls, name: str) -> Converter:
        klass = cls._registry.get(name)
        if klass is None:
            raise KeyError(f"No converter registered for {name!r}")
        return klass()


@Converter.register_named("int")
class IntConverter(Converter):
    def convert(self, value: Any) -> int:
        return int(value)


@Converter.register_named("float")
class FloatConverter(Converter):
    def convert(self, value: Any) -> float:
        return float(value)


@Converter.register_named("str")
class StrConverter(Converter):
    def convert(self, value: Any) -> str:
        return str(value)


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import tempfile

    logging.basicConfig(level=logging.INFO)
    print("=== abc demo ===")

    print("\n--- IStorage (MemoryStorage) ---")
    mem = MemoryStorage()
    mem.write("a.txt", b"hello")
    mem.write("b.txt", b"world")
    print(f"  keys: {mem.keys()}")
    print(f"  read('a.txt'): {mem.read('a.txt')}")
    print(f"  checksum:  {mem.checksum('a.txt')[:16]}...")
    mem.copy("a.txt", "c.txt")
    print(f"  after copy: {sorted(mem.keys())}")

    print("\n--- IStorage (LocalStorage) ---")
    with tempfile.TemporaryDirectory() as td:
        ls = LocalStorage(td)
        ls.write("cfg.json", b'{"k":1}')
        print(f"  exists: {ls.exists('cfg.json')}")
        print(f"  read:   {ls.read('cfg.json')}")

    print("\n--- isinstance with ABC ---")
    print(f"  isinstance(mem, IStorage): {isinstance(mem, IStorage)}")

    print("\n--- TypeError on incomplete subclass ---")
    try:
        class BadStorage(IStorage):
            def read(self, k): ...
        # missing write, delete, exists, keys
        BadStorage()
    except TypeError as e:
        print(f"  TypeError: {str(e)[:60]}...")

    print("\n--- ISerializer ---")
    ser = JsonSerializer()
    data = {"key": "value", "num": 42}
    encoded = ser.encode(data)
    print(f"  content_type: {ser.content_type}")
    print(f"  encoded:  {encoded}")
    print(f"  roundtrip: {ser.roundtrip(data)}")

    print("\n--- Template method (DataPipeline) ---")
    captured: list[str] = []
    import io
    buf = io.StringIO()
    import contextlib
    pipeline = EchoDataPipeline([{"name": " Alice ", "age": 30}, {"name": " Bob ", "age": 25}])
    with contextlib.redirect_stdout(buf):
        n = pipeline.run()
    print(f"  processed {n} records")
    for line in buf.getvalue().splitlines():
        print(f"  → {line}")

    print("\n--- Converter registry ---")
    for name, value in [("int", "42"), ("float", "3.14"), ("str", 99)]:
        result = Converter.get(name).convert(value)
        print(f"  Converter[{name!r}].convert({value!r}) = {result!r}")

    print("\n=== done ===")

For the typing.Protocol alternative — typing.Protocol (PEP 544) provides structural subtyping without requiring explicit inheritance: any class implementing the required methods is automatically a valid Protocol subtype, checked at type-check time (mypy/pyright) but not enforced at runtime unless @runtime_checkable is added; abc.ABC requires explicit inheritance and raises TypeError at instantiation time if methods are missing — use Protocol when you want duck-typing checks in type stubs without coupling third-party code to your base class, ABC when you want runtime enforcement of interface contracts, template method patterns with shared concrete logic, and registration of virtual subclasses. For the zope.interface alternative — zope.interface is a mature third-party interface library used in Zope/Pyramid/Twisted that provides Interface, implementer, and component registries for dependency injection; abc.ABC is stdlib and needs no registry or DI container — use zope.interface for large-scale Zope/Pyramid ecosystems requiring a full component architecture, abc.ABC for standard Python projects needing interface enforcement. The Claude Skills 360 bundle includes abc skill sets covering IStorage with MemoryStorage/LocalStorage concrete backends, ISerializer with JsonSerializer and content_type property, DataPipeline template method with extract/transform/load hooks, ReprMixin/EqMixin/Entity compound mixin, and Converter plugin registry with register_named() decorator. Start with the free tier to try abstract interface design and abc architecture pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free