YAML wrapper.
[python-bulletml.git] / bulletml / bulletyaml.py
1 """BulletYAML implementation.
2
3 BulletYAML is a translation of BulletML into YAML. The structure is
4 mostly the same as the XML version, except BulletRef/FireRef/ActionRef
5 elements are only used if they contain parameters, as YAML has its own
6 intra-document references. Parameterless references are turned into
7 direct YAML references.
8
9 If PyYAML is installed, importing this module automatically registers
10 BulletYAML tags with the default loader and dumper.
11
12 Example BulletYAML document:
13 !BulletML
14 type: vertical
15 actions:
16 top: !ActionDef
17 actions:
18 - !FireDef
19 bullet: !BulletDef {}
20
21 """
22
23 from bulletml import parser
24
25 def register(Loader=None, Dumper=None):
26 """Register BulletYAML types for a Loader and Dumper."""
27 for cls in [parser.Direction, parser.ChangeDirection,
28 parser.Speed, parser.ChangeSpeed, parser.Wait,
29 parser.Tag, parser.Untag, parser.Vanish,
30 parser.Repeat, parser.Accel, parser.BulletDef,
31 parser.BulletRef, parser.ActionDef, parser.ActionRef,
32 parser.FireDef, parser.FireRef, parser.Offset,
33 parser.BulletML]:
34
35 def add(cls, loader, dumper):
36 tag = "!" + cls.__name__
37 if loader:
38 def construct(loader, node):
39 return loader.construct_yaml_object(node, cls)
40 loader.add_constructor(tag, construct)
41 if dumper:
42 def represent(dumper, obj):
43 return dumper.represent_yaml_object(tag, obj, cls)
44 dumper.add_representer(cls, represent)
45
46 add(cls, Loader, Dumper)
47
48 try:
49 import yaml
50 except ImportError:
51 pass
52 else:
53 register(yaml, yaml)