Skip to content

The media-type-version Python API

media_type_version

Extract the format version from a media type string.

VERSION = '0.1.1' module-attribute

The media-type-version library version, semver-like.

Config dataclass

Runtime configuration for the media-type-version library.

Source code in python/src/media_type_version/defs.py
@dataclasses.dataclass(frozen=True)
class Config:
    """Runtime configuration for the media-type-version library."""

    log: logging.Logger
    """The logger to send diagnostic, informational, and error messages to."""

    prefix: str
    """The prefix to expect in the media type string."""

    suffix: str
    """The optional suffix in the media type string."""
log instance-attribute

The logger to send diagnostic, informational, and error messages to.

prefix instance-attribute

The prefix to expect in the media type string.

suffix instance-attribute

The optional suffix in the media type string.

MTVError dataclass

Bases: Exception

An error that occurred while parsing the media type string.

Source code in python/src/media_type_version/defs.py
@dataclasses.dataclass
class MTVError(Exception):
    """An error that occurred while parsing the media type string."""

    def __str__(self) -> str:
        """Provide a human-readable description of the error."""
        return f"Could not parse a media type string: {self!r}"
__str__()

Provide a human-readable description of the error.

Source code in python/src/media_type_version/defs.py
def __str__(self) -> str:
    """Provide a human-readable description of the error."""
    return f"Could not parse a media type string: {self!r}"

extract(cfg, value)

Extract the media type format version as a (major, minor) tuple.

Source code in python/src/media_type_version/impl.py
def extract(cfg: defs.Config, value: str) -> tuple[int, int]:
    """Extract the media type format version as a (major, minor) tuple."""

    def parse_int(comp: str) -> int:
        """Parse a version component into a base-10 integer."""
        if not RE_INT.match(comp):
            raise NonIntegerComponentError(value, comp)

        try:
            return int(comp, base=10)
        except ValueError as err:
            raise NonIntegerComponentError(value, comp) from err

    no_pfx: Final = rm_part(value, cfg.prefix, str.removeprefix, NoPrefixError)
    no_sfx: Final = rm_part(no_pfx, cfg.suffix, str.removesuffix, NoSuffixError)
    no_vdot: Final = no_sfx.removeprefix(".v")
    if no_vdot == no_sfx:
        raise NoVersionError(value, cfg.prefix, cfg.suffix)
    cfg.log.debug("Parsing the media type version part %(vers)r", {"vers": no_vdot})

    match no_vdot.split("."):
        case [major, minor]:
            return parse_int(major), parse_int(minor)

        case _:
            raise TwoComponentsExpectedError(value, no_vdot)