Claude Code for importlib.resources: Python Package Data Access — Claude Skills 360 Blog
Blog / AI / Claude Code for importlib.resources: Python Package Data Access
AI

Claude Code for importlib.resources: Python Package Data Access

Published: December 29, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s importlib.resources module provides a standard API for reading data files bundled with Python packages — works whether the package is installed from a wheel, loaded from a zip archive, or running from source. import importlib.resources as ilr. Modern API (Python 3.9+): ref = ilr.files("mypackage")Traversable; (ref / "data.json").read_text() or (ref / "data.json").read_bytes(). Open file: with ilr.as_file(ref / "model.pkl") as path: load(path) — materializes to disk if needed. Legacy API (3.7+): ilr.read_text("mypackage", "config.toml"), ilr.read_binary("mypackage", "icon.png"), ilr.open_text("mypackage", "template.html", encoding="utf-8"), ilr.contents("mypackage")Iterator[str], ilr.is_resource("mypackage", "data.json")bool. Subdirectories: ilr.files("mypackage.data") — use dotted package path for sub-packages. Backport: importlib_resources (PyPI) for Python < 3.9. Claude Code generates installed package file loaders, config readers, embedded asset accessors, and data bundle managers.

CLAUDE.md for importlib.resources

## importlib.resources Stack
- Stdlib: import importlib.resources as ilr
- Read text:   (ilr.files("mypkg") / "data.json").read_text(encoding="utf-8")
- Read bytes:  (ilr.files("mypkg") / "icon.png").read_bytes()
- As path:     with ilr.as_file(ilr.files("mypkg") / "model.pkl") as p: ...
- List:        [r.name for r in ilr.files("mypkg").iterdir()]
- Legacy:      ilr.read_text("mypkg", "cfg.toml")   # 3.7+
- Note:        use ilr.files() (3.9+) for subdirectory traversal

importlib.resources Package Data Pipeline

# app/resourceutil.py — loader, reader, asset manager, config loader, bundler
from __future__ import annotations

import importlib.resources as ilr
import json
import os
import shutil
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterator


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic resource access helpers
# ─────────────────────────────────────────────────────────────────────────────

def resource_text(
    package: str,
    resource: str,
    encoding: str = "utf-8",
) -> str:
    """
    Read a text resource from a package and return its content as str.

    Example:
        text = resource_text("myapp", "templates/hello.html")
        text = resource_text("myapp.data", "defaults.toml")
    """
    return (ilr.files(package) / resource).read_text(encoding=encoding)


def resource_bytes(package: str, resource: str) -> bytes:
    """
    Read a binary resource from a package and return its content as bytes.

    Example:
        data = resource_bytes("myapp", "assets/logo.png")
        model = resource_bytes("myapp.models", "tfidf.pkl")
    """
    return (ilr.files(package) / resource).read_bytes()


def resource_exists(package: str, resource: str) -> bool:
    """
    Return True if the named resource exists in the package.

    Example:
        resource_exists("myapp", "config.json")   # True or False
    """
    ref = ilr.files(package) / resource
    try:
        return ref.is_file()
    except (FileNotFoundError, TypeError):
        return False


def list_resources(package: str) -> list[str]:
    """
    Return a sorted list of resource names in the top level of a package.

    Example:
        names = list_resources("myapp.data")
        print(names)
    """
    return sorted(r.name for r in ilr.files(package).iterdir())


@contextmanager
def resource_path(package: str, resource: str) -> Iterator[Path]:
    """
    Context manager that yields a real filesystem Path for the resource.
    Materializes zip-embedded resources to a temp file if needed.

    Example:
        with resource_path("myapp", "lib/native.so") as p:
            ctypes.cdll.LoadLibrary(str(p))
    """
    ref = ilr.files(package) / resource
    with ilr.as_file(ref) as path:
        yield Path(path)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Structured config / data loaders
# ─────────────────────────────────────────────────────────────────────────────

def load_json_resource(package: str, resource: str) -> Any:
    """
    Load a JSON resource from a package and return the parsed object.

    Example:
        config = load_json_resource("myapp", "config/defaults.json")
        schema = load_json_resource("myapp.schemas", "user.json")
    """
    text = resource_text(package, resource)
    return json.loads(text)


def load_lines_resource(
    package: str,
    resource: str,
    strip_comments: bool = True,
    encoding: str = "utf-8",
) -> list[str]:
    """
    Load a text resource as a list of non-empty lines.
    Strips lines starting with '#' when strip_comments=True.

    Example:
        words = load_lines_resource("myapp", "data/stopwords.txt")
        patterns = load_lines_resource("myapp", "data/rules.txt", strip_comments=True)
    """
    lines = resource_text(package, resource, encoding=encoding).splitlines()
    result = []
    for line in lines:
        line = line.strip()
        if not line:
            continue
        if strip_comments and line.startswith("#"):
            continue
        result.append(line)
    return result


# ─────────────────────────────────────────────────────────────────────────────
# 3. Asset manager
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class PackageAssets:
    """
    Typed accessor for a package's bundled assets directory.
    Provides read, exists, list, and extract operations.

    Example:
        assets = PackageAssets("myapp", subdir="assets")
        logo = assets.read_bytes("logo.png")
        css  = assets.read_text("style.css")
        assets.extract_all("/tmp/static/")
    """
    package:  str
    subdir:   str = ""
    encoding: str = "utf-8"

    def _ref(self, name: str = "") -> Any:
        base = ilr.files(self.package)
        if self.subdir:
            base = base / self.subdir
        return base / name if name else base

    def read_text(self, name: str) -> str:
        return self._ref(name).read_text(encoding=self.encoding)

    def read_bytes(self, name: str) -> bytes:
        return self._ref(name).read_bytes()

    def exists(self, name: str) -> bool:
        ref = self._ref(name)
        try:
            return ref.is_file()
        except (FileNotFoundError, TypeError):
            return False

    def list(self) -> list[str]:
        return sorted(r.name for r in self._ref().iterdir())

    @contextmanager
    def as_path(self, name: str) -> Iterator[Path]:
        with ilr.as_file(self._ref(name)) as path:
            yield Path(path)

    def extract_all(self, dest_dir: "str | Path") -> list[Path]:
        """
        Copy all assets from this subdir to dest_dir on disk.
        Returns list of written paths.

        Example:
            written = assets.extract_all("/var/www/static")
        """
        dest = Path(dest_dir)
        dest.mkdir(parents=True, exist_ok=True)
        written: list[Path] = []
        for name in self.list():
            out = dest / name
            out.write_bytes(self.read_bytes(name))
            written.append(out)
        return written


# ─────────────────────────────────────────────────────────────────────────────
# 4. Resource discovery and reporting
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class ResourceInfo:
    """Describes one resource in a package."""
    package:  str
    name:     str
    is_file:  bool
    size:     "int | None"  # None for directories or zip-embedded resources


def discover_resources(
    package: str,
    recursive: bool = True,
    prefix: str = "",
) -> list[ResourceInfo]:
    """
    Walk a package's resource tree and return ResourceInfo for each entry.

    Example:
        for ri in discover_resources("myapp"):
            print(ri.package, ri.name, ri.size)
    """
    results: list[ResourceInfo] = []
    base = ilr.files(package)

    def _walk(traversable: Any, current_prefix: str) -> None:
        try:
            children = list(traversable.iterdir())
        except (NotADirectoryError, TypeError):
            return
        for child in children:
            name = current_prefix + child.name
            is_file = child.is_file()
            size: "int | None" = None
            if is_file:
                try:
                    with ilr.as_file(child) as p:
                        size = Path(p).stat().st_size
                except Exception:
                    pass
            results.append(ResourceInfo(package=package, name=name, is_file=is_file, size=size))
            if recursive and not is_file:
                _walk(child, name + "/")

    _walk(base, prefix)
    return sorted(results, key=lambda r: r.name)


# ─────────────────────────────────────────────────────────────────────────────
# Demo (uses __main__ as the "package" via __spec__)
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import importlib.util
    import sys
    import tempfile

    print("=== importlib.resources demo ===")

    # Build a temporary package with bundled data files
    with tempfile.TemporaryDirectory() as tmpdir:
        pkg_dir = Path(tmpdir) / "demopkg"
        pkg_dir.mkdir()
        data_dir = pkg_dir / "data"
        data_dir.mkdir()

        # Write package files
        (pkg_dir / "__init__.py").write_text("")
        (pkg_dir / "config.json").write_text('{"debug": false, "version": "1.0"}')
        (pkg_dir / "data" / "__init__.py").write_text("")
        (pkg_dir / "data" / "words.txt").write_text("hello\n# comment\nworld\nfoo")
        (pkg_dir / "data" / "icon.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 20)

        # Add tmpdir to sys.path so we can import demopkg
        sys.path.insert(0, tmpdir)

        # ── resource_text / resource_bytes ─────────────────────────────────────
        print("\n--- resource_text ---")
        text = resource_text("demopkg", "config.json")
        print(f"  config.json: {text[:60]!r}")

        print("\n--- load_json_resource ---")
        cfg = load_json_resource("demopkg", "config.json")
        print(f"  parsed: {cfg}")

        print("\n--- load_lines_resource ---")
        words = load_lines_resource("demopkg.data", "words.txt", strip_comments=True)
        print(f"  words: {words}")

        # ── list_resources ────────────────────────────────────────────────────
        print("\n--- list_resources ---")
        print(f"  demopkg:      {list_resources('demopkg')}")
        print(f"  demopkg.data: {list_resources('demopkg.data')}")

        # ── resource_exists ───────────────────────────────────────────────────
        print("\n--- resource_exists ---")
        print(f"  config.json exists:   {resource_exists('demopkg', 'config.json')}")
        print(f"  missing.txt exists:   {resource_exists('demopkg', 'missing.txt')}")

        # ── PackageAssets ─────────────────────────────────────────────────────
        print("\n--- PackageAssets ---")
        assets = PackageAssets("demopkg", subdir="data")
        print(f"  list: {assets.list()}")
        print(f"  icon.png size: {len(assets.read_bytes('icon.png'))} bytes")

        # ── discover_resources ─────────────────────────────────────────────────
        print("\n--- discover_resources ---")
        for ri in discover_resources("demopkg", recursive=True):
            size_str = f"{ri.size}B" if ri.size is not None else "dir"
            print(f"  {'FILE' if ri.is_file else 'DIR ':4s} {ri.name:30s}  {size_str}")

        # ── extract_all ────────────────────────────────────────────────────────
        print("\n--- PackageAssets.extract_all ---")
        out_dir = Path(tmpdir) / "extracted"
        written = assets.extract_all(out_dir)
        print(f"  extracted {len(written)} files to {out_dir.name}/")

        sys.path.pop(0)

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

For the pkg_resources (setuptools) alternative — pkg_resources.resource_string("mypackage", "data.json") and pkg_resources.resource_filename() were the standard approach before Python 3.7 and are still found in many projects — always prefer importlib.resources for new code; pkg_resources imports the entire setuptools machinery (slow), while importlib.resources is a lightweight stdlib module. For the __file__ / Path(__file__).parent / "data" direct path alternative — constructing paths relative to __file__ works when running from source on a filesystem, but fails when the package is loaded from a zip or wheel that hasn’t been extracted — use importlib.resources.files() instead; it handles all installation modes correctly including zip imports and namespace packages. The Claude Skills 360 bundle includes importlib.resources skill sets covering resource_text()/resource_bytes()/resource_exists()/list_resources()/resource_path() access helpers, load_json_resource()/load_lines_resource() structured loaders, PackageAssets with read_text()/read_bytes()/exists()/list()/as_path()/extract_all(), and ResourceInfo/discover_resources() tree walker. Start with the free tier to try package resource patterns and importlib.resources 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