Skip to content

Backend

Sub classes

Name Children Inherits
MarkdownParser
mkconvert.parsers.base
Base class for Markdown -> HTML parsers.
HtmlToMarkdownConverter
mkconvert.converters.base
Base class for HTML -> Markdown converters.

Base classes

Name Children Inherits
ABC
abc
Helper class that provides a standard way to create an ABC using
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  1836221132["_core.Backend"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  3481597255["typing.Generic"]
  925645236 --> 1836221132
  2751680898 --> 925645236
  3481597255 --> 1836221132
  2751680898 --> 3481597255

🛈 DocStrings

Bases: ABC

Base class for Markdown parsers and HTML-to-Markdown converters.

Source code in src/mkconvert/_core.py
class Backend[O: Options](ABC):
    """Base class for Markdown parsers and HTML-to-Markdown converters."""

    name: ClassVar[str]
    """Registry name of the backend."""
    requires: ClassVar[tuple[str, ...]]
    """Import names of the packages the backend needs."""
    extra: ClassVar[str]
    """The mkconvert extra that installs these packages."""
    supported_options: ClassVar[frozenset[str]]
    """Common options this backend can set to a non-default value."""
    options_class: ClassVar[type[Options]]

    def __init__(self, options: O | None = None, *, on_unsupported: OnUnsupported = "warn"):
        """Check dependencies and options.

        Args:
            options: Common options; `None` for the defaults.
            on_unsupported: What to do with options this backend cannot honour:
                `"warn"` (ignore them with an `UnsupportedOptionWarning`), `"raise"`
                (`UnsupportedOptionError`) or `"ignore"` (silently).

        Raises:
            MissingDependencyError: A required package is not installed.
            UnsupportedOptionError: Unsupported options are set and
                `on_unsupported="raise"`.
        """
        self.require()
        self.options: O = options if options is not None else cast("O", self.options_class())
        if unsupported := self.unsupported(self.options):
            names = ", ".join(sorted(unsupported))
            msg = f"{self.name!r} does not support option(s): {names}"
            match on_unsupported:
                case "raise":
                    raise UnsupportedOptionError(msg)
                case "warn":
                    warnings.warn(
                        f"{msg}; ignoring them",
                        UnsupportedOptionWarning,
                        skip_file_prefixes=(_PACKAGE_DIR,),
                    )

    @classmethod
    def unsupported(cls, options: Options) -> set[str]:
        """Names of the options in `options` this backend cannot honour."""
        return options.changed() - cls.supported_options

    @classmethod
    def is_available(cls) -> bool:
        """Whether the packages this backend needs are installed."""
        return all(importlib.util.find_spec(pkg) is not None for pkg in cls.requires)

    @classmethod
    def require(cls) -> None:
        """Raise `MissingDependencyError` if a required package is missing."""
        if not cls.is_available():
            pkgs = ", ".join(repr(p) for p in cls.requires)
            msg = (
                f"{cls.name!r} needs the package(s) {pkgs}. "
                f"Install them with: pip install 'mkconvert[{cls.extra}]'"
            )
            raise MissingDependencyError(msg)

    @abstractmethod
    def convert(self, text: str) -> str:
        """Convert `text` and return the result."""

    def __repr__(self) -> str:
        return f"{type(self).__name__}({self.options!r})"

extra class-attribute

extra: str

The mkconvert extra that installs these packages.

name class-attribute

name: str

Registry name of the backend.

requires class-attribute

requires: tuple[str, ...]

Import names of the packages the backend needs.

supported_options class-attribute

supported_options: frozenset[str]

Common options this backend can set to a non-default value.

__init__

__init__(options: O | None = None, *, on_unsupported: OnUnsupported = 'warn')

Check dependencies and options.

Parameters:

Name Type Description Default
options O | None

Common options; None for the defaults.

None
on_unsupported OnUnsupported

What to do with options this backend cannot honour: "warn" (ignore them with an UnsupportedOptionWarning), "raise" (UnsupportedOptionError) or "ignore" (silently).

'warn'

Raises:

Type Description
MissingDependencyError

A required package is not installed.

UnsupportedOptionError

Unsupported options are set and on_unsupported="raise".

Source code in src/mkconvert/_core.py
def __init__(self, options: O | None = None, *, on_unsupported: OnUnsupported = "warn"):
    """Check dependencies and options.

    Args:
        options: Common options; `None` for the defaults.
        on_unsupported: What to do with options this backend cannot honour:
            `"warn"` (ignore them with an `UnsupportedOptionWarning`), `"raise"`
            (`UnsupportedOptionError`) or `"ignore"` (silently).

    Raises:
        MissingDependencyError: A required package is not installed.
        UnsupportedOptionError: Unsupported options are set and
            `on_unsupported="raise"`.
    """
    self.require()
    self.options: O = options if options is not None else cast("O", self.options_class())
    if unsupported := self.unsupported(self.options):
        names = ", ".join(sorted(unsupported))
        msg = f"{self.name!r} does not support option(s): {names}"
        match on_unsupported:
            case "raise":
                raise UnsupportedOptionError(msg)
            case "warn":
                warnings.warn(
                    f"{msg}; ignoring them",
                    UnsupportedOptionWarning,
                    skip_file_prefixes=(_PACKAGE_DIR,),
                )

convert abstractmethod

convert(text: str) -> str

Convert text and return the result.

Source code in src/mkconvert/_core.py
@abstractmethod
def convert(self, text: str) -> str:
    """Convert `text` and return the result."""

is_available classmethod

is_available() -> bool

Whether the packages this backend needs are installed.

Source code in src/mkconvert/_core.py
@classmethod
def is_available(cls) -> bool:
    """Whether the packages this backend needs are installed."""
    return all(importlib.util.find_spec(pkg) is not None for pkg in cls.requires)

require classmethod

require() -> None

Raise MissingDependencyError if a required package is missing.

Source code in src/mkconvert/_core.py
@classmethod
def require(cls) -> None:
    """Raise `MissingDependencyError` if a required package is missing."""
    if not cls.is_available():
        pkgs = ", ".join(repr(p) for p in cls.requires)
        msg = (
            f"{cls.name!r} needs the package(s) {pkgs}. "
            f"Install them with: pip install 'mkconvert[{cls.extra}]'"
        )
        raise MissingDependencyError(msg)

unsupported classmethod

unsupported(options: Options) -> set[str]

Names of the options in options this backend cannot honour.

Source code in src/mkconvert/_core.py
@classmethod
def unsupported(cls, options: Options) -> set[str]:
    """Names of the options in `options` this backend cannot honour."""
    return options.changed() - cls.supported_options

:fa-brands-github: Show source on GitHub