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 toget()) to a module name.decode_key(name)— map a module name (what the plugin package discovery finds) to a public key (whatkeys()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(), andexclude— operates in key space: public keys. - The internal state — the item cache,
excludelookups after the key-space check, module import, and plugin package discovery (pkgutil.iter_modules) — operates in module space. get()/__getitem__()callencode_key()exactly once, before the cache lookup. Everything downstream works with the module name.keys()deduplicates module names in module space and appliesdecode_key()to each of them.excludetakes public keys (it is compared beforeencode_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:
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 | |
|---|---|
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.