Skip to content

Config

Config

Bases: dict

Object carrying parameters needed for task execution. Config also describe which tasks configures (tasks field) and and on which other configs depends (uses field). Thus, config carry all information needed to assemble task chain.

Typical usage:

chain = Config(task_data_dir, 'config.yaml').chain()

Source code in taskchain/config.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
class Config(dict):
    """
    Object carrying parameters needed for task execution.
    Config also describe which tasks configures (`tasks` field) and
    and on which other configs depends (`uses` field).
    Thus, config carry all information needed to assemble task chain.

    Typical usage:
    ```python
    chain = Config(task_data_dir, 'config.yaml').chain()
    ```
    """

    RESERVED_PARAMETER_NAMES = [
        'tasks',
        'excluded_tasks',
        'uses',
        'human_readable_data_name',
        'configs',
        'for_namespaces',
        'main_part',
    ]

    def __init__(
        self,
        base_dir: Union[Path, str, None] = None,
        filepath: Union[Path, str] = None,
        global_vars: Union[Any, None] = None,
        context: Union[None, dict, str, Path, Context, Iterable] = None,
        name: str = None,
        namespace: str = None,
        data: Dict = None,
        part: str = None,
    ):
        """

        Args:
            base_dir: dir with task data, required for task data persistence
            filepath: json or yaml with config data
            global_vars: data to fill placeholders inf config data such as `{DATA_DIR}`
            context: config which amend or overwrite data of this config
            name: specify name of config directly, required when not using filepath
            namespace: used by chains, allow work with same tasks with multiple configs in one chain
            data: alternative for `filepath`, inject data directly
            part: for multi config files, name of file part
        """
        super().__init__()

        self.base_dir = base_dir
        self._name = None
        self.namespace = namespace
        self._data = None
        self.context = Context.prepare_context(context, global_vars=global_vars)
        self.global_vars = global_vars
        self._filepath = filepath
        self._part = part

        if filepath is not None:
            if '#' in str(self._filepath):
                self._filepath, self._part = str(self._filepath).split('#')
            filepath = Path(self._filepath)
            name_parts = filepath.name.split('.')
            extension = name_parts[-1]
            self._name = '.'.join(name_parts[:-1])
            if extension == 'json':
                self._data = json.load(filepath.open())
            elif extension == 'yaml':
                self._data = yaml.load(filepath.open(), Loader=yaml.Loader)
            else:
                raise ValueError(f'Unknown file extension for config file `{filepath}`')

        if data is not None:
            self._data = data
        if name is not None:
            self._name = name

        self._prepare()

    def _prepare(self, create_objects=True):
        if self._data and 'configs' in self._data:
            self._get_part()
            self._update_uses()
        if self.context is not None:
            self.apply_context(self.context)
        self._validate_data()
        if self.global_vars is not None:
            self.apply_global_vars(self.global_vars)
        if create_objects:
            self.prepare_objects()

    def _get_part(self):
        assert len(self._data) == 1, 'Multipart configs should contain only field `configs`'

        if self._part:
            try:
                self._data = self._data['configs'][self._part]
            except KeyError:
                raise KeyError(f'Part `{self._part}` not found in config `{self}`')
            return

        assert (
            len([c for c in self._data['configs'] if 'main_part' in c]) < 2
        ), f'More then one part of config `self` are marked as main'
        for part_name, part in self._data['configs'].items():
            if part.get('main_part', False):
                self._data = part
                self._part = part_name
                return

        raise KeyError(f'No part specified for multi config `{self}`')

    def _update_uses(self):
        if self._filepath is None or 'uses' not in self._data:
            return
        self._data['uses'] = list_or_str_to_list(self._data['uses'])
        for i, use in enumerate(self._data['uses']):
            if isinstance(use, str) and use.startswith('#'):
                self._data['uses'][i] = str(self._filepath) + use

    @property
    def name(self) -> str:
        if self._name is None:
            raise ValueError(f'Missing config name')
        if self._part:
            return f'{self._name}#{self._part}'
        return self._name

    def get_name_for_persistence(self, *args, **kwargs) -> str:
        """Used for creating filename in task data persistence, should uniquely define config"""
        return self.name

    @property
    def fullname(self):
        """Name with namespace"""
        if self.namespace is None:
            return f'{self.name}'
        return f'{self.namespace}::{self.name}'

    @property
    def repr_name(self) -> str:
        """Should be unique representation of this config"""
        if self._filepath:
            if self.namespace is None:
                name = str(self._filepath)
            else:
                name = f'{self.namespace}::{self._filepath}'
            if self._part:
                return f'{name}#{self._part}'
            return name
        return self.fullname

    @property
    def repr_name_without_namespace(self) -> str:
        """Unique representation of this config without namespace"""
        return self.repr_name.split('::')[-1]

    def __str__(self):
        return self.fullname

    def __repr__(self):
        return f'<config: {self}>'

    @property
    def data(self):
        if self._data is None:
            raise ValueError(f'Data of config `{self}` not initialized')
        return self._data

    def __getitem__(self, item):
        return self.data[item]

    def __getattr__(self, item):
        if item in self:
            return self.data[item]
        return self.__getattribute__(item)

    def get(self, item, default=None):
        return self.data.get(item, default)

    def __contains__(self, item):
        return item in self.data

    def apply_context(self, context: Context):
        """Amend or rewrite data of config by data from context"""
        self._data.update(deepcopy(context.data))
        if self.namespace:
            for namespace, data in context.for_namespaces.items():
                if self.namespace == namespace:
                    self._data.update(deepcopy(data))

    def _validate_data(self):
        """Check correct format of data"""
        if self._data is None:
            return

        data = self._data
        uses = data.get('uses', [])
        if not (isinstance(uses, Iterable) or isinstance(uses, str)):
            raise ValueError(f'`uses` of config `{self}` have to be list or str')

        tasks = data.get('tasks', [])
        if not (isinstance(tasks, Iterable) or isinstance(tasks, str)):
            raise ValueError(f'`tasks` of config `{self}` have to list or str')

    def apply_global_vars(self, global_vars):
        search_and_replace_placeholders(self._data, global_vars)

    def prepare_objects(self):
        """Instantiate objects described in config"""
        if self._data is None:
            return

        def _instancelize_clazz(clazz, args, kwargs):
            obj = instantiate_clazz(clazz, args, kwargs)
            if not isinstance(obj, ParameterObject):
                LOGGER.warning(f'Object `{obj}` in config `{self}` is not instance of ParameterObject')
            if not hasattr(obj, 'repr'):
                raise Exception(f'Object `{obj}` does not implement `repr` property')
            return obj

        for key, value in self._data.items():
            self._data[key] = find_and_instantiate_clazz(value, instancelize_clazz_fce=_instancelize_clazz)

    def chain(self, parameter_mode=True, **kwargs):
        """Create chain from this config"""
        from .chain import Chain

        return Chain(self, parameter_mode=parameter_mode, **kwargs)

    def get_original_config(self):
        """Get self of config from which this one is derived"""
        return self

fullname property

Name with namespace

repr_name: str property

Should be unique representation of this config

repr_name_without_namespace: str property

Unique representation of this config without namespace

__init__(base_dir=None, filepath=None, global_vars=None, context=None, name=None, namespace=None, data=None, part=None)

Parameters:

Name Type Description Default
base_dir Union[Path, str, None]

dir with task data, required for task data persistence

None
filepath Union[Path, str]

json or yaml with config data

None
global_vars Union[Any, None]

data to fill placeholders inf config data such as {DATA_DIR}

None
context Union[None, dict, str, Path, Context, Iterable]

config which amend or overwrite data of this config

None
name str

specify name of config directly, required when not using filepath

None
namespace str

used by chains, allow work with same tasks with multiple configs in one chain

None
data Dict

alternative for filepath, inject data directly

None
part str

for multi config files, name of file part

None
Source code in taskchain/config.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def __init__(
    self,
    base_dir: Union[Path, str, None] = None,
    filepath: Union[Path, str] = None,
    global_vars: Union[Any, None] = None,
    context: Union[None, dict, str, Path, Context, Iterable] = None,
    name: str = None,
    namespace: str = None,
    data: Dict = None,
    part: str = None,
):
    """

    Args:
        base_dir: dir with task data, required for task data persistence
        filepath: json or yaml with config data
        global_vars: data to fill placeholders inf config data such as `{DATA_DIR}`
        context: config which amend or overwrite data of this config
        name: specify name of config directly, required when not using filepath
        namespace: used by chains, allow work with same tasks with multiple configs in one chain
        data: alternative for `filepath`, inject data directly
        part: for multi config files, name of file part
    """
    super().__init__()

    self.base_dir = base_dir
    self._name = None
    self.namespace = namespace
    self._data = None
    self.context = Context.prepare_context(context, global_vars=global_vars)
    self.global_vars = global_vars
    self._filepath = filepath
    self._part = part

    if filepath is not None:
        if '#' in str(self._filepath):
            self._filepath, self._part = str(self._filepath).split('#')
        filepath = Path(self._filepath)
        name_parts = filepath.name.split('.')
        extension = name_parts[-1]
        self._name = '.'.join(name_parts[:-1])
        if extension == 'json':
            self._data = json.load(filepath.open())
        elif extension == 'yaml':
            self._data = yaml.load(filepath.open(), Loader=yaml.Loader)
        else:
            raise ValueError(f'Unknown file extension for config file `{filepath}`')

    if data is not None:
        self._data = data
    if name is not None:
        self._name = name

    self._prepare()

get_name_for_persistence(*args, **kwargs)

Used for creating filename in task data persistence, should uniquely define config

Source code in taskchain/config.py
149
150
151
def get_name_for_persistence(self, *args, **kwargs) -> str:
    """Used for creating filename in task data persistence, should uniquely define config"""
    return self.name

apply_context(context)

Amend or rewrite data of config by data from context

Source code in taskchain/config.py
204
205
206
207
208
209
210
def apply_context(self, context: Context):
    """Amend or rewrite data of config by data from context"""
    self._data.update(deepcopy(context.data))
    if self.namespace:
        for namespace, data in context.for_namespaces.items():
            if self.namespace == namespace:
                self._data.update(deepcopy(data))

prepare_objects()

Instantiate objects described in config

Source code in taskchain/config.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def prepare_objects(self):
    """Instantiate objects described in config"""
    if self._data is None:
        return

    def _instancelize_clazz(clazz, args, kwargs):
        obj = instantiate_clazz(clazz, args, kwargs)
        if not isinstance(obj, ParameterObject):
            LOGGER.warning(f'Object `{obj}` in config `{self}` is not instance of ParameterObject')
        if not hasattr(obj, 'repr'):
            raise Exception(f'Object `{obj}` does not implement `repr` property')
        return obj

    for key, value in self._data.items():
        self._data[key] = find_and_instantiate_clazz(value, instancelize_clazz_fce=_instancelize_clazz)

chain(parameter_mode=True, **kwargs)

Create chain from this config

Source code in taskchain/config.py
245
246
247
248
249
def chain(self, parameter_mode=True, **kwargs):
    """Create chain from this config"""
    from .chain import Chain

    return Chain(self, parameter_mode=parameter_mode, **kwargs)

get_original_config()

Get self of config from which this one is derived

Source code in taskchain/config.py
251
252
253
def get_original_config(self):
    """Get self of config from which this one is derived"""
    return self

Context

Bases: Config

Config intended for amend or rewrite other configs

Source code in taskchain/config.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
class Context(Config):
    """
    Config intended for amend or rewrite other configs
    """

    def __repr__(self):
        return f'<context: {self}>'

    @staticmethod
    def prepare_context(
        context_config: Union[None, dict, str, Path, Context, Iterable], namespace=None, global_vars=None
    ) -> Union[Context, None]:
        """Helper function for instantiating Context from various sources"""
        context = None
        if context_config is None:
            return
        elif type(context_config) is str or isinstance(context_config, Path):
            context = Context(filepath=context_config, namespace=namespace)
        elif type(context_config) is dict:
            value_reprs = [f'{k}:{v}' for k, v in sorted(context_config.items())]
            context = Context(data=context_config, name=f'dict_context({",".join(value_reprs)})', namespace=namespace)
        elif isinstance(context_config, Context):
            context = context_config
        elif isinstance(context_config, Iterable):
            contexts = map(
                partial(Context.prepare_context, namespace=namespace, global_vars=global_vars), context_config
            )
            context = Context.merge_contexts(contexts)

        if context is None:
            raise ValueError(f'Unknown context type `{type(context_config)}`')

        current_context_data = context.for_namespaces[namespace] if namespace else context
        if 'uses' not in current_context_data:
            return context

        if global_vars is not None:
            search_and_replace_placeholders(current_context_data['uses'], global_vars)

        contexts = [context]
        for use in list_or_str_to_list(current_context_data['uses']):
            if matched := re.match(r'(.*) as (.*)', use):
                # uses context with namespace
                filepath = matched[1]
                sub_namespace = f'{context.namespace}::{matched[2]}' if context.namespace else matched[2]
            else:
                filepath = use
                sub_namespace = context.namespace if context.namespace else None
            contexts.append(Context.prepare_context(filepath, sub_namespace, global_vars=global_vars))
        if namespace:
            del context.for_namespaces[namespace]['uses']
        else:
            del context._data['uses']
        return Context.prepare_context(contexts)

    @staticmethod
    def merge_contexts(contexts: Iterable[Context]) -> Context:
        """
        Helper function for merging multiple Context to one

        Later contexts have higher priority and rewrite data of earlier contexts if there is conflict in data.
        """
        data = {}
        names = []
        for_namespaces = defaultdict(dict)
        for context in contexts:
            data.update(context.data)
            names.append(context.name)
            for namespace, values in context.for_namespaces.items():
                for_namespaces[namespace].update(values)
        data['for_namespaces'] = for_namespaces
        return Context(data=data, name=';'.join(names))

    def _prepare(self):
        if 'for_namespaces' in self._data:
            self.for_namespaces = self._data['for_namespaces']
        else:
            self.for_namespaces = {}

        if self.namespace is not None:
            self.for_namespaces = {f'{self.namespace}::{k}': v for k, v in self.for_namespaces.items()}
            self.for_namespaces[self.namespace] = {
                k: v for k, v in self._data.items() if k not in Context.RESERVED_PARAMETER_NAMES or k == 'uses'
            }
            self._data = {}
        super()._prepare(create_objects=False)

prepare_context(context_config, namespace=None, global_vars=None) staticmethod

Helper function for instantiating Context from various sources

Source code in taskchain/config.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
@staticmethod
def prepare_context(
    context_config: Union[None, dict, str, Path, Context, Iterable], namespace=None, global_vars=None
) -> Union[Context, None]:
    """Helper function for instantiating Context from various sources"""
    context = None
    if context_config is None:
        return
    elif type(context_config) is str or isinstance(context_config, Path):
        context = Context(filepath=context_config, namespace=namespace)
    elif type(context_config) is dict:
        value_reprs = [f'{k}:{v}' for k, v in sorted(context_config.items())]
        context = Context(data=context_config, name=f'dict_context({",".join(value_reprs)})', namespace=namespace)
    elif isinstance(context_config, Context):
        context = context_config
    elif isinstance(context_config, Iterable):
        contexts = map(
            partial(Context.prepare_context, namespace=namespace, global_vars=global_vars), context_config
        )
        context = Context.merge_contexts(contexts)

    if context is None:
        raise ValueError(f'Unknown context type `{type(context_config)}`')

    current_context_data = context.for_namespaces[namespace] if namespace else context
    if 'uses' not in current_context_data:
        return context

    if global_vars is not None:
        search_and_replace_placeholders(current_context_data['uses'], global_vars)

    contexts = [context]
    for use in list_or_str_to_list(current_context_data['uses']):
        if matched := re.match(r'(.*) as (.*)', use):
            # uses context with namespace
            filepath = matched[1]
            sub_namespace = f'{context.namespace}::{matched[2]}' if context.namespace else matched[2]
        else:
            filepath = use
            sub_namespace = context.namespace if context.namespace else None
        contexts.append(Context.prepare_context(filepath, sub_namespace, global_vars=global_vars))
    if namespace:
        del context.for_namespaces[namespace]['uses']
    else:
        del context._data['uses']
    return Context.prepare_context(contexts)

merge_contexts(contexts) staticmethod

Helper function for merging multiple Context to one

Later contexts have higher priority and rewrite data of earlier contexts if there is conflict in data.

Source code in taskchain/config.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
@staticmethod
def merge_contexts(contexts: Iterable[Context]) -> Context:
    """
    Helper function for merging multiple Context to one

    Later contexts have higher priority and rewrite data of earlier contexts if there is conflict in data.
    """
    data = {}
    names = []
    for_namespaces = defaultdict(dict)
    for context in contexts:
        data.update(context.data)
        names.append(context.name)
        for namespace, values in context.for_namespaces.items():
            for_namespaces[namespace].update(values)
    data['for_namespaces'] = for_namespaces
    return Context(data=data, name=';'.join(names))