22eeb1480f3f1a6a096246b21cb0e8aef1ef7cb8
[hooke.git] / hooke / util / yaml.py
1 # Copyright
2
3 """Add representers to YAML to support Hooke.
4
5 Without introspection, YAML cannot decide how to save some
6 objects.  By refusing to save these objects, we obviously loose
7 that information, so make sure the things you drop are either
8 stored somewhere else or not important.
9
10 >>> import yaml
11 >>> a = numpy.array([1,2,3])
12 >>> print yaml.dump(a)
13 null
14 ...
15 <BLANKLINE>
16
17 The default behavior is to crash.
18
19 >>> yaml.Dumper.yaml_representers.pop(numpy.ndarray)  # doctest: +ELLIPSIS
20 <function ndarray_representer at 0x...>
21 >>> print yaml.dump(a)
22 Traceback (most recent call last):
23   ...
24     if data in [None, ()]:
25 TypeError: data type not understood
26
27 Restore the representer for future tests.
28
29 >>> yaml.add_representer(numpy.ndarray, ndarray_representer)
30 """
31
32 from __future__ import absolute_import
33 import sys
34
35 import numpy
36 import yaml #from yaml.representer import Representer
37
38 from ..curve import Data
39
40
41 if False: # YAML dump debugging code
42     """To help isolate data types etc. that give YAML problems.
43
44     This is usually caused by external C modules (e.g. numpy) that
45     define new types (e.g. numpy.dtype) which YAML cannot inspect.
46     """
47     def ignore_aliases(data):
48         print data, type(data)
49         sys.stdout.flush()
50         if data in [None, ()]:
51             return True
52         if isinstance(data, (str, unicode, bool, int, float)):
53             return True
54     yaml.representer.SafeRepresenter.ignore_aliases = staticmethod(
55         ignore_aliases)
56
57 def ndarray_representer(dumper, data):
58     return dumper.represent_none(None)
59 yaml.add_representer(numpy.ndarray, ndarray_representer)
60 yaml.add_representer(Data, ndarray_representer)