BaseVisitor

class mlfarm.core.BaseVisitor[source]

This is a fake implementation of the visitor pattern. It has the purpose of offering a way to transform nested dicts and lists. The BaseVisitor class is the Identity transform so it returs a clone of the object.

>>> bv = BaseVisitor()
>>> a = [1, {'a': 2}, 3]
>>> b = bv.visit(a)
>>> b
[1, {'a': 2}, 3]
>>> b[0] = 2
>>> a
[1, {'a': 2}, 3]
visit(obj)[source]

This method is to be called on the object to be transformed.

Parameters:obj (str | object | list | dict) – Object to be transformed.
Returns:The output of the transformation.
Return type:str | object | list | dict
visit_dict(obj)[source]

This is here to be overwriten in a child class. The argument is a dict.

Parameters:obj (dict) – Object to be transformed.
Returns:The same object.
Return type:str | object | list | dict
>>> class DictVisitor(BaseVisitor):
...     def visit_dict(self, obj):
...         try:
...             return { **obj, 'ab': obj['a'] + obj['b'] }
...         except:
...             return super().visit_dict(obj)
...
>>> dv = DictVisitor()
>>> a = [{'a': 'ok'}, {'b': 1}, {'a': 'o', 'b': 'k'}]
>>> dv.visit(a)
[{'a': 'ok'}, {'b': 1}, {'a': 'o', 'b': 'k', 'ab': 'ok'}]
visit_list(obj)[source]

This is here to be overwriten in a child class. The argument is a list.

Parameters:obj (list) – Object to be transformed.
Returns:The same object.
Return type:str | object | list | dict
>>> class ListVisitor(BaseVisitor):
...     def visit_list(self, obj):
...         try:
...             return sum(obj)
...         except:
...             return super().visit_list(obj)
...
>>> lv = ListVisitor()
>>> a = {'a': [1, 2, 3], 'b': 'ok', 'c': [1, 2, 'nok']}
>>> lv.visit(a)
{'a': 6, 'b': 'ok', 'c': [1, 2, 'nok']}
visit_obj(obj)[source]

This is here to be overwriten in a child class. We know the argument is not list, dict or str.

Parameters:obj (object) – Object to be transformed.
Returns:The same object.
Return type:str | object | list | dict
>>> class ObjVisitor(BaseVisitor):
...     def visit_obj(self, obj):
...         if obj % 2 == 0:
...             return obj // 2
...         else:
...             return (obj + 1) // 2
...
>>> ov = ObjVisitor()
>>> a = list(range(10))
>>> ov.visit(a)
[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
visit_str(obj)[source]

This is here to be overwriten in a child class. The argument is a string.

Parameters:obj (str) – Object to be transformed.
Returns:The same object.
Return type:str | object | list | dict
>>> class StrVisitor(BaseVisitor):
...     def visit_str(self, obj):
...         if obj == 'nok':
...             return 'error'
...         return obj
...
>>> sv = StrVisitor()
>>> a = [{'a': 'ok'}, {'b': 1}, {'c': 'nok'}]
>>> sv.visit(a)
[{'a': 'ok'}, {'b': 1}, {'c': 'error'}]