Basic Usage

Define My Rules

In the example above, numpy objects are translated as the serialized bytes, it is not as visible as we expected. Besides, you may think that the dictionary which is expressed with {} format is so ugly that you want to optimize the expression.

You can define your own rule like the example below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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
import re

import numpy as np

from potc import transvars
from potc.fixture import rule, Addons
from potc.rules import builtin_dict


@rule(type_=np.ndarray)
def ndarray_(v, addon: Addons):
    with addon.transaction():
        return addon.obj(np, 'np').array(v.tolist())


_VAR_NAME = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')


@rule(type_=dict)
def my_dict(v: dict, addon: Addons):
    if all([isinstance(key, str) and _VAR_NAME.fullmatch(key) for key in v.keys()]):
        return addon.val(type(v))(**v)
    else:
        addon.unprocessable()  # give up rule replacing


if __name__ == '__main__':
    _code = transvars({
        'np_objects': {
            'a': np.array([[1, 2, ], [3, 4]]),
            'b': {
                'c': np.array([1, 2, 3]),
                'd': np.zeros((2, 3)),
                't': 233,
            },
            'e': {
                '0': np.array([1, 2]),
                'p': 2j,
                'f': {
                    123: np.ones((3, 2)),
                    None: np.zeros((1, 5)),
                },
                'g': {
                    'a': 'dict here.'
                }
            },
        },
        'np_module': np,
    }, [
        ndarray_,  # rule for np.ndarray
        (my_dict, builtin_dict,),  # rule for dict, before `builtin_dict`
    ], reformat='pep8')  # auto reformat the code
    print(_code)

The output result (as well as the dumped script) should be

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import numpy
import numpy as np

__all__ = ['np_module', 'np_objects']
np_module = numpy
np_objects = dict(a=np.array([[1, 2], [3, 4]]),
                  b=dict(c=np.array([1, 2, 3]),
                         d=np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
                         t=233),
                  e={
                      '0': np.array([1, 2]),
                      'p': 2j,
                      'f': {
                          123: np.array([[1.0, 1.0], [1.0, 1.0], [1.0, 1.0]]),
                          None: np.array([[0.0, 0.0, 0.0, 0.0, 0.0]])
                      },
                      'g': dict(a='dict here.')
                  })

Now you can see the dictionaries will be expressed with dict form when the keys is allowed to do so, the np.ndarray objects will be expressed with the visible format as well.