ContentsFoundations to FrontierBezhig

eng-lab/hwe/core/__init__.py

All lab code. Download this file.

"""The core: the equations YOU write, one file per topic, checked by each lab's tests.

Every file in this folder starts as docstrings only. Its module docstring names
the lab steps that fill it in. The rest of the engine (the design loader, the
report, the CAD boundary) calls these functions through `load`, so the report
shows "not written yet" until your code exists, and uses your code once it does.

`load` has one extra job. When the environment variable ENGLAB_IMPL names a
folder, it imports <name>.py from that folder instead of from here. That switch
runs a second implementation against the same tests; you never need it.
"""
from __future__ import annotations

import importlib
import importlib.util
import os
import sys
from pathlib import Path
from types import ModuleType

_cache: dict[tuple[str, str], ModuleType] = {}


def load(name: str) -> ModuleType:
    """Return the core module `name` (for example "hover"): yours, or ENGLAB_IMPL's."""
    impl = os.environ.get("ENGLAB_IMPL")
    if not impl:
        return importlib.import_module(f"hwe.core.{name}")
    key = (impl, name)
    if key not in _cache:
        path = Path(impl).resolve() / f"{name}.py"
        spec = importlib.util.spec_from_file_location(f"englab_impl_{name}", path)
        if spec is None or spec.loader is None:
            raise ImportError(f"ENGLAB_IMPL has no {name}.py: {path}")
        module = importlib.util.module_from_spec(spec)
        sys.modules[spec.name] = module
        spec.loader.exec_module(module)
        _cache[key] = module
    return _cache[key]


def written(func, *args, **kwargs) -> bool:
    """True if calling func does not raise NotImplementedError (used by the report)."""
    try:
        func(*args, **kwargs)
    except NotImplementedError:
        return False
    except Exception:
        return True
    return True