Skip to content

Custom Key Mapping

By default, a plugin is addressed by the name of its module: the module my_plugin.py in a plugin package defines the plugin my_plugin. Some projects, however, want to address plugins with logical names that differ from module names. For example, a NOC-style profile loader deals with dot-separated profile names ("Cisco.IOS") while the actual modules use flat names (cisco__ios.py).

Since version 3.1.0 the Loader class provides two public hooks for mapping between these two name spaces:

  • encode_key(name) — map a public key (what the user passes to get()) to a module name.
  • decode_key(name) — map a module name (what the plugin package discovery finds) to a public key (what keys() reports).

Both hooks are identity by default, so the behavior of Loader is unchanged unless a subclass overrides them.

Key Space vs Module Space

The contract is the following:

  • The public surface — get(), __getitem__, keys(), and exclude — operates in key space: public keys.
  • The internal state — the item cache, exclude lookups after the key-space check, module import, and plugin package discovery (pkgutil.iter_modules) — operates in module space.
  • get() / __getitem__() call encode_key() exactly once, before the cache lookup. Everything downstream works with the module name.
  • keys() deduplicates module names in module space and applies decode_key() to each of them.
  • exclude takes public keys (it is compared before encode_key()).
  • The item cache is indexed by module names. Two distinct public keys that encode to the same module name correctly share the same cache slot and return the same item.

Example

A dot-separated-to-flat mapping, like the NOC profile loader:

loader.py
import re

from gufo.loader import Loader


def mangle_profile_name(name: str) -> str:
    """Map a logical profile name to a flat module name."""
    name = name.lower().replace(".", "__")
    return re.sub(r"_{2,}", "_", name)  # "Cisco.IOS" -> "cisco__ios"


class ProfileLoader(Loader[type[BaseProfile]]):
    def encode_key(self, name: str) -> str:
        return mangle_profile_name(name)


loader = ProfileLoader(base="myproject.profiles")
# The user code works with logical names:
kls = loader.get("Cisco.IOS")

In this example only encode_key() is overridden: mangle_profile_name() is irreversible (it lower-cases and collapses underscores), so the reverse mapping does not exist. This is acceptable — see the warning below.

A reversible mapping (e.g. lower-casing) allows overriding both hooks, so that keys() reports the public keys:

loader.py
1
2
3
4
5
6
class LowerCaseLoader(Loader[BasePlugin]):
    def encode_key(self, name: str) -> str:
        return name.lower()

    def decode_key(self, name: str) -> str:
        return name.upper()

Warning: Irreversible Mappings and keys()

If decode_key() is not overridden (identity) or is overridden irreversibly, keys() reports module names as public keys. As long as encode_key() is idempotent on module names (re-mangling an already mangled name returns the same name), values() and items() remain correct: they take the decoded keys, re-encode them, and resolve to the same modules. If encode_key() is not idempotent on module names, values() / items() may resolve to nothing — the public keys are simply not recoverable from module names. In such cases enumerate modules in module space if you need to iterate all plugins.