optionally sort named extensions

NamedExtensionManager can optionally order loaded extensions to match the
names parameter.
This commit is contained in:
Daniel Rocco 2013-05-17 23:25:22 -04:00
parent ab58eaa0a4
commit 41388cd070
2 changed files with 30 additions and 2 deletions
stevedore

@ -4,7 +4,7 @@ from .extension import ExtensionManager
class NamedExtensionManager(ExtensionManager):
"""Loads only the named extensions.
This is useful for explictly enabling extensions in a
This is useful for explicitly enabling extensions in a
configuration file, for example.
:param namespace: The namespace for the entry points.
@ -22,10 +22,14 @@ class NamedExtensionManager(ExtensionManager):
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param name_order: If true, sort the loaded extensions to match the
order used in ``names``.
:type name_order: bool
"""
def __init__(self, namespace, names,
invoke_on_load=False, invoke_args=(), invoke_kwds={}):
invoke_on_load=False, invoke_args=(), invoke_kwds={},
name_order=False):
self._names = names
super(NamedExtensionManager, self).__init__(
namespace,
@ -34,6 +38,9 @@ class NamedExtensionManager(ExtensionManager):
invoke_kwds=invoke_kwds,
)
if name_order:
self.extensions.sort(key=lambda x: names.index(x.name))
def _load_one_plugin(self, ep, invoke_on_load, invoke_args, invoke_kwds):
# Check the name before going any further to prevent
# undesirable code from being loaded at all if we are not

@ -35,3 +35,24 @@ def test_enabled_before_load():
)
actual = em.names()
assert actual == []
def test_extensions_listed_in_name_order():
# Since we don't know the "natural" order of the extensions, run
# the test both ways: if the sorting is broken, one of them will
# fail
em = named.NamedExtensionManager(
'stevedore.test.extension',
names='t1 t2',
name_order=True
)
actual = em.names()
assert actual == ['t1', 't2']
em = named.NamedExtensionManager(
'stevedore.test.extension',
names='t2 t1',
name_order=True
)
actual = em.names()
assert actual == ['t2', 't1']