Skip to content

Registry API

sweet_tea.registry.Registry

Global registry for class definitions that can be instantiated via factories.

This registry automatically discovers and registers classes from packages, supporting optional dependencies that may not be installed. Classes with missing dependencies are skipped with a warning rather than failing registration.

The registry supports typed lookups for abstract factories, allowing filtering by inheritance hierarchy.

Thread-safe: All registry operations are synchronized to prevent race conditions in multi-threaded environments.

Source code in sweet_tea/registry.py
class Registry:
    """
    Global registry for class definitions that can be instantiated via factories.

    This registry automatically discovers and registers classes from packages,
    supporting optional dependencies that may not be installed. Classes with
    missing dependencies are skipped with a warning rather than failing registration.

    The registry supports typed lookups for abstract factories, allowing filtering
    by inheritance hierarchy.

    Thread-safe: All registry operations are synchronized to prevent race conditions
    in multi-threaded environments.
    """

    # Threading lock for synchronizing registry operations
    __lock = threading.RLock()

    # This is the registry of packages
    __registry: list[Entry] = []

    __lookup: dict[Any, list[Entry]] = {}

    __lookup_keys: list[Any] = []

    # Logger instance using the global settings
    __logger = logging.getLogger()

    @classmethod
    def entries(cls) -> list[Entry]:
        """Get all registered entries."""
        with cls.__lock:
            return cls.__registry.copy()

    @classmethod
    def typed_entries(cls, lookup_type: Any = Any) -> list[Entry]:
        """
        Get entries that are subclasses of the specified type.

        Args:
            lookup_type: The base class to filter by. Defaults to Any.

        Returns:
            List of entries where the class_def is a subclass of lookup_type.
        """
        with cls.__lock:
            if lookup_type not in cls.__lookup_keys:
                cls.__lookup_keys.append(lookup_type)
                if lookup_type is Any:
                    # Any matches everything - return all entries without filtering
                    cls.__lookup[lookup_type] = cls.__registry.copy()
                else:
                    cls.__lookup[lookup_type] = [
                        filtered_type
                        for filtered_type in cls.__registry
                        if issubclass(filtered_type.class_def, lookup_type)
                    ]
            return cls.__lookup[lookup_type].copy()

    @classmethod
    def register(
        cls, key: str, class_def: type, library: str = "", label: str = ""
    ) -> None:
        """
        Register a class with the registry.

        Args:
            key: Name used to reference the class for instantiation.
            class_def: The class type to register.
            library: Name of the library the class belongs to.
            label: Optional label for categorizing classes (e.g., for different environments).
        """
        new_entry = Entry(
            key=key.lower(),
            class_def=class_def,
            library=library.lower(),
            label=label.lower(),
        )

        with cls.__lock:
            # Add entry if it is not currently present. Prevents duplicate entry.
            if new_entry not in cls.__registry:
                cls.__registry.append(new_entry)
                # Refresh every previously-queried lookup slot whose type matches
                # this class. Without this, ancestor-type slots cached before the
                # registration go stale (see GH #6).
                for lookup_type in cls.__lookup_keys:
                    if lookup_type is Any:
                        cls.__lookup[lookup_type].append(new_entry)
                    elif isinstance(lookup_type, type) and issubclass(
                        class_def, lookup_type
                    ):
                        cls.__lookup[lookup_type].append(new_entry)

    @classmethod
    def fill_registry(
        cls,
        path: str | None = None,
        module: str | None = None,
        library: str = "",
        label: str = "",
        exclude: Iterable[str] | None = None,
    ) -> None:
        """
        Recursively scan and register classes from packages starting from the given path.

        This method automatically discovers all classes in the package hierarchy,
        supporting optional dependencies by gracefully skipping modules that fail
        to import due to missing packages.

        Both regular packages and implicit namespace packages (PEP 420) are traversed;
        no flag is needed to opt in to the latter. Directories that cannot be imported
        are ignored — see :meth:`__is_namespace_package` for the exact rules.

        Directories that *are* importable but should not be registered — ``tests``,
        ``fixtures``, ``examples`` — cannot be detected automatically, since they are
        legitimate Python. Name them via ``exclude``:

        .. code-block:: python

            Registry.fill_registry(exclude=["*.tests", "*.examples"])

        Excluding a package prunes its whole subtree, so a single pattern is enough to
        drop everything beneath it.

        Args:
            path: Package path where modules are located. If None, uses the caller's module path.
            module: Name of the root module. If None, inferred from path.
            library: Name of the library for categorization.
            label: Optional label for categorizing classes.
            exclude: Glob patterns matched case-sensitively against the full dotted
                module path (``mypkg.sub.tests``). Matching modules are not imported and
                matching packages are not descended into. Applies to regular and
                namespace packages alike.
        """
        with cls.__lock:
            # Determine the path to scan
            if path is None:
                _module = inspect.getmodule(inspect.stack()[1][0])
                if _module is None or _module.__file__ is None:
                    raise SweetTeaError("Cannot determine module path automatically")
                path = str(Path(_module.__file__).parent)

            # Ensure path is a string
            path_str = str(path)

            # Make sure the root module is correctly specified
            if module is None:
                module = os.path.basename(path_str)

            if not library:
                library = module

            # Location of package
            pkg_dir = path_str

            # Materialised once so the recursive calls below share a single tuple rather
            # than re-consuming a caller-supplied iterator, which would be exhausted
            # after the first subpackage.
            exclude_patterns = tuple(exclude or ())

            # Loop over the modules. If it is a package, the make recursive call, otherwise for each non-package
            # module imports the module and registers it.
            for name, is_a_package in cls.__iter_package_children(pkg_dir):
                pkg_name = f"{module}.{name}"
                if cls.__is_excluded(pkg_name, exclude_patterns):
                    # Logged rather than dropped silently; an under-filled registry with
                    # no explanation is the failure mode this whole area keeps hitting.
                    cls.__logger.debug(
                        f"Skipping {pkg_name}: matched an exclude pattern"
                    )
                    continue

                if not is_a_package:
                    cls.__add_entry_to_registry(
                        label=label, library=library, name_of_package=pkg_name
                    )
                else:
                    # Make recursive call to the
                    cls.fill_registry(
                        path=os.path.join(pkg_dir, name),
                        module=pkg_name,
                        library=library,
                        label=label,
                        exclude=exclude_patterns,
                    )

    @classmethod
    def __is_excluded(cls, dotted_name: str, patterns: tuple[str, ...]) -> bool:
        """
        Test a dotted module path against the caller's exclude patterns.

        Uses :func:`fnmatch.fnmatchcase` rather than :func:`fnmatch.fnmatch`; the latter
        applies ``os.path.normcase``, making matches case-insensitive on Windows. Module
        names are case-sensitive, so matching must not vary by platform.

        Args:
            dotted_name: Full dotted path of the module or package under consideration.
            patterns: Glob patterns supplied by the caller.

        Returns:
            True when any pattern matches.
        """
        return any(fnmatch.fnmatchcase(dotted_name, pattern) for pattern in patterns)

    @classmethod
    def __iter_package_children(cls, pkg_dir: str) -> list[tuple[str, bool]]:
        """
        List the importable children of a package directory.

        Extends :func:`pkgutil.iter_modules`, which reports a subdirectory only when it
        contains an ``__init__``. Implicit namespace packages (PEP 420) have no
        ``__init__`` and are therefore invisible to it — not reported as a package and
        not reported as a module — so their contents were silently skipped during
        registry filling.

        Args:
            pkg_dir: Directory to scan.

        Returns:
            Sorted (name, is_a_package) pairs, with namespace packages included.
        """
        children: dict[str, bool] = {
            name: is_a_package
            for _, name, is_a_package in pkgutil.iter_modules([pkg_dir])
        }

        if os.path.isdir(pkg_dir):
            with os.scandir(pkg_dir) as directory_entries:
                for directory_entry in directory_entries:
                    if directory_entry.name in children:
                        continue
                    if not directory_entry.is_dir(follow_symlinks=False):
                        continue
                    if cls.__is_namespace_package(
                        directory_entry.name, directory_entry.path
                    ):
                        children[directory_entry.name] = True

        return sorted(children.items())

    @classmethod
    def __is_namespace_package(cls, name: str, path: str) -> bool:
        """
        Decide whether a directory lacking ``__init__`` should be treated as a package.

        ``__init__.py`` used to act as a de-facto opt-in marker, so treating every bare
        directory as a package risks descending into directories that are not packages
        at all. These filters restore that boundary without making users opt in to
        namespace support.

        Args:
            name: Directory name.
            path: Full path to the directory.

        Returns:
            True when the directory is a plausible namespace package.
        """
        # Not importable under any circumstances - 'my-pkg', 'v1.2', 'sample data'.
        if not name.isidentifier():
            return False

        # Hidden ('.venv', '.git') and private or generated ('__pycache__') directories.
        if name.startswith(".") or name.startswith("_"):
            return False

        # A namespace package must eventually lead to a module; a directory holding only
        # data files is not one. Nested namespace packages are legal, so this recurses.
        with os.scandir(path) as directory_entries:
            for directory_entry in directory_entries:
                if directory_entry.is_file(follow_symlinks=False):
                    if inspect.getmodulename(directory_entry.name) is not None:
                        return True
                elif directory_entry.is_dir(follow_symlinks=False):
                    if cls.__is_namespace_package(
                        directory_entry.name, directory_entry.path
                    ):
                        return True

        return False

    @classmethod
    def __add_entry_to_registry(
        cls, label: str, library: str, name_of_package: str
    ) -> None:
        """
        Import a module and register all classes defined in it.

        Handles optional dependencies by issuing warnings for ImportError/ModuleNotFoundError
        and continuing, while raising SweetTeaError for other exceptions.

        Args:
            label: Optional label for categorizing classes.
            library: Name of the library the classes belong to.
            name_of_package: Full module name to import and scan.

        Raises:
            SweetTeaError: For non-import related errors during module processing.
        """
        try:
            # exec("import " + name_of_package)
            module = importlib.import_module(name_of_package)

            classes = []
            for name, obj in inspect.getmembers(module, inspect.isclass):
                if obj.__module__ == name_of_package:
                    classes.append((name, obj))

            for class_name, class_def in classes:
                Registry.register(
                    key=class_name.lower(),
                    class_def=class_def,
                    library=library,
                    label=label,
                )

        except (ImportError, ModuleNotFoundError):
            # Optional dependency not installed - issue warning and skip this module
            warnings.warn(
                f"Skipping module {name_of_package} due to missing optional dependency",
                SweetTeaWarning,
                stacklevel=2,
            )
            # Continue without registering this module
        except Exception:
            # Other errors (e.g., syntax errors, runtime errors) should still fail
            error_message = traceback.format_exc()
            cls.__logger.error(
                f"Error processing module {name_of_package}: {error_message}"
            )
            raise SweetTeaError(error_message)

__add_entry_to_registry(label, library, name_of_package) classmethod

Import a module and register all classes defined in it.

Handles optional dependencies by issuing warnings for ImportError/ModuleNotFoundError and continuing, while raising SweetTeaError for other exceptions.

Parameters:

Name Type Description Default
label str

Optional label for categorizing classes.

required
library str

Name of the library the classes belong to.

required
name_of_package str

Full module name to import and scan.

required

Raises:

Type Description
SweetTeaError

For non-import related errors during module processing.

Source code in sweet_tea/registry.py
@classmethod
def __add_entry_to_registry(
    cls, label: str, library: str, name_of_package: str
) -> None:
    """
    Import a module and register all classes defined in it.

    Handles optional dependencies by issuing warnings for ImportError/ModuleNotFoundError
    and continuing, while raising SweetTeaError for other exceptions.

    Args:
        label: Optional label for categorizing classes.
        library: Name of the library the classes belong to.
        name_of_package: Full module name to import and scan.

    Raises:
        SweetTeaError: For non-import related errors during module processing.
    """
    try:
        # exec("import " + name_of_package)
        module = importlib.import_module(name_of_package)

        classes = []
        for name, obj in inspect.getmembers(module, inspect.isclass):
            if obj.__module__ == name_of_package:
                classes.append((name, obj))

        for class_name, class_def in classes:
            Registry.register(
                key=class_name.lower(),
                class_def=class_def,
                library=library,
                label=label,
            )

    except (ImportError, ModuleNotFoundError):
        # Optional dependency not installed - issue warning and skip this module
        warnings.warn(
            f"Skipping module {name_of_package} due to missing optional dependency",
            SweetTeaWarning,
            stacklevel=2,
        )
        # Continue without registering this module
    except Exception:
        # Other errors (e.g., syntax errors, runtime errors) should still fail
        error_message = traceback.format_exc()
        cls.__logger.error(
            f"Error processing module {name_of_package}: {error_message}"
        )
        raise SweetTeaError(error_message)

__is_excluded(dotted_name, patterns) classmethod

Test a dotted module path against the caller's exclude patterns.

Uses :func:fnmatch.fnmatchcase rather than :func:fnmatch.fnmatch; the latter applies os.path.normcase, making matches case-insensitive on Windows. Module names are case-sensitive, so matching must not vary by platform.

Parameters:

Name Type Description Default
dotted_name str

Full dotted path of the module or package under consideration.

required
patterns tuple[str, ...]

Glob patterns supplied by the caller.

required

Returns:

Type Description
bool

True when any pattern matches.

Source code in sweet_tea/registry.py
@classmethod
def __is_excluded(cls, dotted_name: str, patterns: tuple[str, ...]) -> bool:
    """
    Test a dotted module path against the caller's exclude patterns.

    Uses :func:`fnmatch.fnmatchcase` rather than :func:`fnmatch.fnmatch`; the latter
    applies ``os.path.normcase``, making matches case-insensitive on Windows. Module
    names are case-sensitive, so matching must not vary by platform.

    Args:
        dotted_name: Full dotted path of the module or package under consideration.
        patterns: Glob patterns supplied by the caller.

    Returns:
        True when any pattern matches.
    """
    return any(fnmatch.fnmatchcase(dotted_name, pattern) for pattern in patterns)

__is_namespace_package(name, path) classmethod

Decide whether a directory lacking __init__ should be treated as a package.

__init__.py used to act as a de-facto opt-in marker, so treating every bare directory as a package risks descending into directories that are not packages at all. These filters restore that boundary without making users opt in to namespace support.

Parameters:

Name Type Description Default
name str

Directory name.

required
path str

Full path to the directory.

required

Returns:

Type Description
bool

True when the directory is a plausible namespace package.

Source code in sweet_tea/registry.py
@classmethod
def __is_namespace_package(cls, name: str, path: str) -> bool:
    """
    Decide whether a directory lacking ``__init__`` should be treated as a package.

    ``__init__.py`` used to act as a de-facto opt-in marker, so treating every bare
    directory as a package risks descending into directories that are not packages
    at all. These filters restore that boundary without making users opt in to
    namespace support.

    Args:
        name: Directory name.
        path: Full path to the directory.

    Returns:
        True when the directory is a plausible namespace package.
    """
    # Not importable under any circumstances - 'my-pkg', 'v1.2', 'sample data'.
    if not name.isidentifier():
        return False

    # Hidden ('.venv', '.git') and private or generated ('__pycache__') directories.
    if name.startswith(".") or name.startswith("_"):
        return False

    # A namespace package must eventually lead to a module; a directory holding only
    # data files is not one. Nested namespace packages are legal, so this recurses.
    with os.scandir(path) as directory_entries:
        for directory_entry in directory_entries:
            if directory_entry.is_file(follow_symlinks=False):
                if inspect.getmodulename(directory_entry.name) is not None:
                    return True
            elif directory_entry.is_dir(follow_symlinks=False):
                if cls.__is_namespace_package(
                    directory_entry.name, directory_entry.path
                ):
                    return True

    return False

__iter_package_children(pkg_dir) classmethod

List the importable children of a package directory.

Extends :func:pkgutil.iter_modules, which reports a subdirectory only when it contains an __init__. Implicit namespace packages (PEP 420) have no __init__ and are therefore invisible to it — not reported as a package and not reported as a module — so their contents were silently skipped during registry filling.

Parameters:

Name Type Description Default
pkg_dir str

Directory to scan.

required

Returns:

Type Description
list[tuple[str, bool]]

Sorted (name, is_a_package) pairs, with namespace packages included.

Source code in sweet_tea/registry.py
@classmethod
def __iter_package_children(cls, pkg_dir: str) -> list[tuple[str, bool]]:
    """
    List the importable children of a package directory.

    Extends :func:`pkgutil.iter_modules`, which reports a subdirectory only when it
    contains an ``__init__``. Implicit namespace packages (PEP 420) have no
    ``__init__`` and are therefore invisible to it — not reported as a package and
    not reported as a module — so their contents were silently skipped during
    registry filling.

    Args:
        pkg_dir: Directory to scan.

    Returns:
        Sorted (name, is_a_package) pairs, with namespace packages included.
    """
    children: dict[str, bool] = {
        name: is_a_package
        for _, name, is_a_package in pkgutil.iter_modules([pkg_dir])
    }

    if os.path.isdir(pkg_dir):
        with os.scandir(pkg_dir) as directory_entries:
            for directory_entry in directory_entries:
                if directory_entry.name in children:
                    continue
                if not directory_entry.is_dir(follow_symlinks=False):
                    continue
                if cls.__is_namespace_package(
                    directory_entry.name, directory_entry.path
                ):
                    children[directory_entry.name] = True

    return sorted(children.items())

entries() classmethod

Get all registered entries.

Source code in sweet_tea/registry.py
@classmethod
def entries(cls) -> list[Entry]:
    """Get all registered entries."""
    with cls.__lock:
        return cls.__registry.copy()

fill_registry(path=None, module=None, library='', label='', exclude=None) classmethod

Recursively scan and register classes from packages starting from the given path.

This method automatically discovers all classes in the package hierarchy, supporting optional dependencies by gracefully skipping modules that fail to import due to missing packages.

Both regular packages and implicit namespace packages (PEP 420) are traversed; no flag is needed to opt in to the latter. Directories that cannot be imported are ignored — see :meth:__is_namespace_package for the exact rules.

Directories that are importable but should not be registered — tests, fixtures, examples — cannot be detected automatically, since they are legitimate Python. Name them via exclude:

.. code-block:: python

Registry.fill_registry(exclude=["*.tests", "*.examples"])

Excluding a package prunes its whole subtree, so a single pattern is enough to drop everything beneath it.

Parameters:

Name Type Description Default
path str | None

Package path where modules are located. If None, uses the caller's module path.

None
module str | None

Name of the root module. If None, inferred from path.

None
library str

Name of the library for categorization.

''
label str

Optional label for categorizing classes.

''
exclude Iterable[str] | None

Glob patterns matched case-sensitively against the full dotted module path (mypkg.sub.tests). Matching modules are not imported and matching packages are not descended into. Applies to regular and namespace packages alike.

None
Source code in sweet_tea/registry.py
@classmethod
def fill_registry(
    cls,
    path: str | None = None,
    module: str | None = None,
    library: str = "",
    label: str = "",
    exclude: Iterable[str] | None = None,
) -> None:
    """
    Recursively scan and register classes from packages starting from the given path.

    This method automatically discovers all classes in the package hierarchy,
    supporting optional dependencies by gracefully skipping modules that fail
    to import due to missing packages.

    Both regular packages and implicit namespace packages (PEP 420) are traversed;
    no flag is needed to opt in to the latter. Directories that cannot be imported
    are ignored — see :meth:`__is_namespace_package` for the exact rules.

    Directories that *are* importable but should not be registered — ``tests``,
    ``fixtures``, ``examples`` — cannot be detected automatically, since they are
    legitimate Python. Name them via ``exclude``:

    .. code-block:: python

        Registry.fill_registry(exclude=["*.tests", "*.examples"])

    Excluding a package prunes its whole subtree, so a single pattern is enough to
    drop everything beneath it.

    Args:
        path: Package path where modules are located. If None, uses the caller's module path.
        module: Name of the root module. If None, inferred from path.
        library: Name of the library for categorization.
        label: Optional label for categorizing classes.
        exclude: Glob patterns matched case-sensitively against the full dotted
            module path (``mypkg.sub.tests``). Matching modules are not imported and
            matching packages are not descended into. Applies to regular and
            namespace packages alike.
    """
    with cls.__lock:
        # Determine the path to scan
        if path is None:
            _module = inspect.getmodule(inspect.stack()[1][0])
            if _module is None or _module.__file__ is None:
                raise SweetTeaError("Cannot determine module path automatically")
            path = str(Path(_module.__file__).parent)

        # Ensure path is a string
        path_str = str(path)

        # Make sure the root module is correctly specified
        if module is None:
            module = os.path.basename(path_str)

        if not library:
            library = module

        # Location of package
        pkg_dir = path_str

        # Materialised once so the recursive calls below share a single tuple rather
        # than re-consuming a caller-supplied iterator, which would be exhausted
        # after the first subpackage.
        exclude_patterns = tuple(exclude or ())

        # Loop over the modules. If it is a package, the make recursive call, otherwise for each non-package
        # module imports the module and registers it.
        for name, is_a_package in cls.__iter_package_children(pkg_dir):
            pkg_name = f"{module}.{name}"
            if cls.__is_excluded(pkg_name, exclude_patterns):
                # Logged rather than dropped silently; an under-filled registry with
                # no explanation is the failure mode this whole area keeps hitting.
                cls.__logger.debug(
                    f"Skipping {pkg_name}: matched an exclude pattern"
                )
                continue

            if not is_a_package:
                cls.__add_entry_to_registry(
                    label=label, library=library, name_of_package=pkg_name
                )
            else:
                # Make recursive call to the
                cls.fill_registry(
                    path=os.path.join(pkg_dir, name),
                    module=pkg_name,
                    library=library,
                    label=label,
                    exclude=exclude_patterns,
                )

register(key, class_def, library='', label='') classmethod

Register a class with the registry.

Parameters:

Name Type Description Default
key str

Name used to reference the class for instantiation.

required
class_def type

The class type to register.

required
library str

Name of the library the class belongs to.

''
label str

Optional label for categorizing classes (e.g., for different environments).

''
Source code in sweet_tea/registry.py
@classmethod
def register(
    cls, key: str, class_def: type, library: str = "", label: str = ""
) -> None:
    """
    Register a class with the registry.

    Args:
        key: Name used to reference the class for instantiation.
        class_def: The class type to register.
        library: Name of the library the class belongs to.
        label: Optional label for categorizing classes (e.g., for different environments).
    """
    new_entry = Entry(
        key=key.lower(),
        class_def=class_def,
        library=library.lower(),
        label=label.lower(),
    )

    with cls.__lock:
        # Add entry if it is not currently present. Prevents duplicate entry.
        if new_entry not in cls.__registry:
            cls.__registry.append(new_entry)
            # Refresh every previously-queried lookup slot whose type matches
            # this class. Without this, ancestor-type slots cached before the
            # registration go stale (see GH #6).
            for lookup_type in cls.__lookup_keys:
                if lookup_type is Any:
                    cls.__lookup[lookup_type].append(new_entry)
                elif isinstance(lookup_type, type) and issubclass(
                    class_def, lookup_type
                ):
                    cls.__lookup[lookup_type].append(new_entry)

typed_entries(lookup_type=Any) classmethod

Get entries that are subclasses of the specified type.

Parameters:

Name Type Description Default
lookup_type Any

The base class to filter by. Defaults to Any.

Any

Returns:

Type Description
list[Entry]

List of entries where the class_def is a subclass of lookup_type.

Source code in sweet_tea/registry.py
@classmethod
def typed_entries(cls, lookup_type: Any = Any) -> list[Entry]:
    """
    Get entries that are subclasses of the specified type.

    Args:
        lookup_type: The base class to filter by. Defaults to Any.

    Returns:
        List of entries where the class_def is a subclass of lookup_type.
    """
    with cls.__lock:
        if lookup_type not in cls.__lookup_keys:
            cls.__lookup_keys.append(lookup_type)
            if lookup_type is Any:
                # Any matches everything - return all entries without filtering
                cls.__lookup[lookup_type] = cls.__registry.copy()
            else:
                cls.__lookup[lookup_type] = [
                    filtered_type
                    for filtered_type in cls.__registry
                    if issubclass(filtered_type.class_def, lookup_type)
                ]
        return cls.__lookup[lookup_type].copy()

Methods

register()

sweet_tea.registry.Registry.register(key, class_def, library='', label='') classmethod

Register a class with the registry.

Parameters:

Name Type Description Default
key str

Name used to reference the class for instantiation.

required
class_def type

The class type to register.

required
library str

Name of the library the class belongs to.

''
label str

Optional label for categorizing classes (e.g., for different environments).

''
Source code in sweet_tea/registry.py
@classmethod
def register(
    cls, key: str, class_def: type, library: str = "", label: str = ""
) -> None:
    """
    Register a class with the registry.

    Args:
        key: Name used to reference the class for instantiation.
        class_def: The class type to register.
        library: Name of the library the class belongs to.
        label: Optional label for categorizing classes (e.g., for different environments).
    """
    new_entry = Entry(
        key=key.lower(),
        class_def=class_def,
        library=library.lower(),
        label=label.lower(),
    )

    with cls.__lock:
        # Add entry if it is not currently present. Prevents duplicate entry.
        if new_entry not in cls.__registry:
            cls.__registry.append(new_entry)
            # Refresh every previously-queried lookup slot whose type matches
            # this class. Without this, ancestor-type slots cached before the
            # registration go stale (see GH #6).
            for lookup_type in cls.__lookup_keys:
                if lookup_type is Any:
                    cls.__lookup[lookup_type].append(new_entry)
                elif isinstance(lookup_type, type) and issubclass(
                    class_def, lookup_type
                ):
                    cls.__lookup[lookup_type].append(new_entry)

entries()

sweet_tea.registry.Registry.entries() classmethod

Get all registered entries.

Source code in sweet_tea/registry.py
@classmethod
def entries(cls) -> list[Entry]:
    """Get all registered entries."""
    with cls.__lock:
        return cls.__registry.copy()

typed_entries()

sweet_tea.registry.Registry.typed_entries(lookup_type=Any) classmethod

Get entries that are subclasses of the specified type.

Parameters:

Name Type Description Default
lookup_type Any

The base class to filter by. Defaults to Any.

Any

Returns:

Type Description
list[Entry]

List of entries where the class_def is a subclass of lookup_type.

Source code in sweet_tea/registry.py
@classmethod
def typed_entries(cls, lookup_type: Any = Any) -> list[Entry]:
    """
    Get entries that are subclasses of the specified type.

    Args:
        lookup_type: The base class to filter by. Defaults to Any.

    Returns:
        List of entries where the class_def is a subclass of lookup_type.
    """
    with cls.__lock:
        if lookup_type not in cls.__lookup_keys:
            cls.__lookup_keys.append(lookup_type)
            if lookup_type is Any:
                # Any matches everything - return all entries without filtering
                cls.__lookup[lookup_type] = cls.__registry.copy()
            else:
                cls.__lookup[lookup_type] = [
                    filtered_type
                    for filtered_type in cls.__registry
                    if issubclass(filtered_type.class_def, lookup_type)
                ]
        return cls.__lookup[lookup_type].copy()

fill_registry()

sweet_tea.registry.Registry.fill_registry(path=None, module=None, library='', label='', exclude=None) classmethod

Recursively scan and register classes from packages starting from the given path.

This method automatically discovers all classes in the package hierarchy, supporting optional dependencies by gracefully skipping modules that fail to import due to missing packages.

Both regular packages and implicit namespace packages (PEP 420) are traversed; no flag is needed to opt in to the latter. Directories that cannot be imported are ignored — see :meth:__is_namespace_package for the exact rules.

Directories that are importable but should not be registered — tests, fixtures, examples — cannot be detected automatically, since they are legitimate Python. Name them via exclude:

.. code-block:: python

Registry.fill_registry(exclude=["*.tests", "*.examples"])

Excluding a package prunes its whole subtree, so a single pattern is enough to drop everything beneath it.

Parameters:

Name Type Description Default
path str | None

Package path where modules are located. If None, uses the caller's module path.

None
module str | None

Name of the root module. If None, inferred from path.

None
library str

Name of the library for categorization.

''
label str

Optional label for categorizing classes.

''
exclude Iterable[str] | None

Glob patterns matched case-sensitively against the full dotted module path (mypkg.sub.tests). Matching modules are not imported and matching packages are not descended into. Applies to regular and namespace packages alike.

None
Source code in sweet_tea/registry.py
@classmethod
def fill_registry(
    cls,
    path: str | None = None,
    module: str | None = None,
    library: str = "",
    label: str = "",
    exclude: Iterable[str] | None = None,
) -> None:
    """
    Recursively scan and register classes from packages starting from the given path.

    This method automatically discovers all classes in the package hierarchy,
    supporting optional dependencies by gracefully skipping modules that fail
    to import due to missing packages.

    Both regular packages and implicit namespace packages (PEP 420) are traversed;
    no flag is needed to opt in to the latter. Directories that cannot be imported
    are ignored — see :meth:`__is_namespace_package` for the exact rules.

    Directories that *are* importable but should not be registered — ``tests``,
    ``fixtures``, ``examples`` — cannot be detected automatically, since they are
    legitimate Python. Name them via ``exclude``:

    .. code-block:: python

        Registry.fill_registry(exclude=["*.tests", "*.examples"])

    Excluding a package prunes its whole subtree, so a single pattern is enough to
    drop everything beneath it.

    Args:
        path: Package path where modules are located. If None, uses the caller's module path.
        module: Name of the root module. If None, inferred from path.
        library: Name of the library for categorization.
        label: Optional label for categorizing classes.
        exclude: Glob patterns matched case-sensitively against the full dotted
            module path (``mypkg.sub.tests``). Matching modules are not imported and
            matching packages are not descended into. Applies to regular and
            namespace packages alike.
    """
    with cls.__lock:
        # Determine the path to scan
        if path is None:
            _module = inspect.getmodule(inspect.stack()[1][0])
            if _module is None or _module.__file__ is None:
                raise SweetTeaError("Cannot determine module path automatically")
            path = str(Path(_module.__file__).parent)

        # Ensure path is a string
        path_str = str(path)

        # Make sure the root module is correctly specified
        if module is None:
            module = os.path.basename(path_str)

        if not library:
            library = module

        # Location of package
        pkg_dir = path_str

        # Materialised once so the recursive calls below share a single tuple rather
        # than re-consuming a caller-supplied iterator, which would be exhausted
        # after the first subpackage.
        exclude_patterns = tuple(exclude or ())

        # Loop over the modules. If it is a package, the make recursive call, otherwise for each non-package
        # module imports the module and registers it.
        for name, is_a_package in cls.__iter_package_children(pkg_dir):
            pkg_name = f"{module}.{name}"
            if cls.__is_excluded(pkg_name, exclude_patterns):
                # Logged rather than dropped silently; an under-filled registry with
                # no explanation is the failure mode this whole area keeps hitting.
                cls.__logger.debug(
                    f"Skipping {pkg_name}: matched an exclude pattern"
                )
                continue

            if not is_a_package:
                cls.__add_entry_to_registry(
                    label=label, library=library, name_of_package=pkg_name
                )
            else:
                # Make recursive call to the
                cls.fill_registry(
                    path=os.path.join(pkg_dir, name),
                    module=pkg_name,
                    library=library,
                    label=label,
                    exclude=exclude_patterns,
                )