Skip to content

Commit

Permalink
fix: Prevent loading of unused backends
Browse files Browse the repository at this point in the history
This change changes how the backends are imported,
instead of importing all of them every backend is
loaded lazy only when its needed.

This solves the problem that dependencies from unused
backends need to be installed even if the are not
used (e.g. symspellpy depends on editdistpy which
needs to be build from source on Windows requiring a
compiler ...).

PR #17: #17
  • Loading branch information
tobiasah authored Sep 5, 2023
1 parent 1e16dd2 commit 12062ff
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/mkdocs_spellcheck/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,37 @@
from mkdocs.config.config_options import Type as MkType
from mkdocs.plugins import BasePlugin
from mkdocs.structure.pages import Page
from symspellpy import SymSpell

from mkdocs_spellcheck.backends import codespell, symspellpy
from mkdocs_spellcheck.backends import Backend
from mkdocs_spellcheck.loggers import get_logger
from mkdocs_spellcheck.words import get_words

logger = get_logger(__name__)


backends_map: dict[str, Any] = {
"symspellpy": symspellpy.SymspellpyBackend,
"codespell": codespell.CodespellBackend,
}
def load_backend(name: str) -> Backend:
"""Load the specified backend.
This function imports the specified backend and returns its class.
It is important not to import the backends at the top level, as
they may not be installed.
Arguments:
name: The name of the backend to load.
Returns:
The backend class.
"""
if name == "symspellpy":
from mkdocs_spellcheck.backends import symspellpy

return symspellpy.SymspellpyBackend
elif name == "codespell":
from mkdocs_spellcheck.backends import codespell

return codespell.CodespellBackend
else:
raise ValueError(f"Unknown backend: {name}")


class SpellCheckPlugin(BasePlugin):
Expand Down Expand Up @@ -53,7 +71,6 @@ class SpellCheckPlugin(BasePlugin):

def __init__(self) -> None: # noqa: D107
self.known_words: set[str] = set()
self.spell: SymSpell = None
super().__init__()

def on_config(self, config: Config, **kwargs: Any) -> Config:
Expand Down Expand Up @@ -93,7 +110,7 @@ def on_config(self, config: Config, **kwargs: Any) -> Config:
backend_config = {}
else:
backend_name, backend_config = next(iter(backend_conf.items()))
self.backends[backend_name] = backends_map[backend_name](
self.backends[backend_name] = load_backend(backend_name)(
known_words=self.known_words,
config=backend_config,
)
Expand Down

0 comments on commit 12062ff

Please sign in to comment.