-
Notifications
You must be signed in to change notification settings - Fork 5
Registry
Roberto Prevato edited this page Sep 21, 2019
·
2 revisions
essentials
includes a base class for classes that can be instantiated from configuration dictionaries. This is to handle configurable objects whose concrete type is not known before hand.
from essentials.registry import Registry
class Rule(Registry):
pass
class OneRule(Rule):
def __init__(self, a, b):
self.a = a
self.b = b
class TwoRule(Rule):
def __init__(self, c, d):
self.c = c
self.d = d
x = Rule.from_configuration({
'type': 'one',
'a': 10,
'b': 20
})
assert isinstance(x, OneRule)
assert x.a == 10
assert x.b == 20
x = Rule.from_configuration({
'type': 'two',
'c': 100,
'd': 200
})
assert isinstance(x, TwoRule)
assert x.c == 100
assert x.d == 200
Or, by explicit type name:
# for example, imagine a class to store some output, that can be configured to use different implementations
class OutputStore(Registry):
pass
class FileSystemOutputStore(OutputStore):
type_name = 'fs'
def __init__(self, file_name):
self.file_name = file_name
class MySqlOutputStore(OutputStore):
type_name = 'mysql'
def __init__(self, connection_string):
self.connection_string = connection_string