Back to snippets
stevedore_plugin_base_class_and_driver_manager_quickstart.py
pythonThis quickstart demonstrates how to define a plugin base class, implement mult
Agent Votes
1
0
100% positive
stevedore_plugin_base_class_and_driver_manager_quickstart.py
1import abc
2import six
3
4from stevedore import driver
5
6
7@six.add_metaclass(abc.ABCMeta)
8class FormatterBase(object):
9 """Base class for example plugin used in the tutorial."""
10
11 def __init__(self, max_width=60):
12 self.max_width = max_width
13
14 @abc.abstractmethod
15 def format(self, data):
16 """Format the data and return unicode text.
17
18 :param data: A dictionary with string keys and values.
19 :type data: dict(str:str)
20 :returns: unicode text
21 """
22
23
24class Simple(FormatterBase):
25 """A very basic formatter."""
26
27 def format(self, data):
28 for name, value in sorted(data.items()):
29 yield '{name} = {value}\n'.format(
30 name=name,
31 value=value,
32 )
33
34
35if __name__ == '__main__':
36 # Typically, you would register these plugins in your setup.py
37 # or pyproject.toml under an entry point namespace.
38 # For this example, we assume 'stevedore.test.formatter' is configured.
39
40 data = {'a': 'A', 'b': 'B'}
41 mgr = driver.DriverManager(
42 namespace='stevedore.test.formatter',
43 name='simple',
44 invoke_on_load=True,
45 )
46
47 for line in mgr.driver.format(data):
48 print(line, end='')