BulletML.FromDocument: Type detector. Various setstate bug fixes.
[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 """Register a class in a new variable scope."""
37 tag = "!" + cls.__name__
38 if loader:
39 def construct(loader, node):
40 """Construct an object."""
41 return loader.construct_yaml_object(node, cls)
42 loader.add_constructor(tag, construct)
43 if dumper:
44 def represent(dumper, obj):
45 """Represent an object."""
46 return dumper.represent_yaml_object(tag, obj, cls)
47 dumper.add_representer(cls, represent)
48
49 add(cls, Loader, Dumper)
50
51 try:
52 import yaml
53 except ImportError:
54 pass
55 else:
56 register(yaml, yaml)