1 '''example code for yaml magic from pyyaml.org documentation.
2 see http://pyyaml.org/wiki/PyYAMLDocumentation#Constructorsrepresentersresolvers'''
5 #def dice_constructor(Dice, data):
6 #major, minor =[int(x) for x in data.split('d')]
7 #return Dice(major, minor)
9 class Dice(yaml
.YAMLObject
):
11 yaml_pattern
= re
.compile('^\d+d\d+$')
12 def __init__(self
, major
, minor
):
16 return "Dice(%s,%s)" % (self
.major
, self
.minor
)
18 return "%sd%s" % (self
.major
, self
.minor
)
20 def to_yaml(cls
, dumper
, data
):
21 return dumper
.represent_scalar(cls
.yaml_tag
, cls
.yaml_repr(data
)) #not sure this is right
23 def from_yaml(cls
, loader
, node
):
24 data
= loader
.construct_scalar(node
)
25 major
, minor
= [int(x
) for x
in data
.split('d')]
26 return cls(major
, minor
)
28 class Foo(yaml
.YAMLObject
):
30 yaml_pattern
= re
.compile('foo(.*)')
31 def __init__(self
, value
):
34 return "Foo(%s)" %(self
.value
)
36 return "foo%s" % self
.value
38 def to_yaml(cls
, dumper
, data
):
39 return dumper
.represent_scalar(cls
.yaml_tag
, cls
.yaml_repr(data
)) #not sure this is right
41 def from_yaml(cls
, loader
, node
):
42 match
= re
.search(cls
.yaml_pattern
, loader
.construct_scalar(node
))
44 return Foo(match
.group(1))
46 return Foo(loader
.construct_scalar(node
))
48 class FirstResolver(yaml
.YAMLObject
):
51 def __init__(self
, extra
):
52 if extra
: some_attr
=extra
54 def from_yaml(cls
, loader
, node
):
55 data
= loader
.construct_scalar(node
)
58 class SecondResolver(FirstResolver
):
62 #teach PyYAML that any untagged scalar with the path [a] has an implict tag !first
63 yaml
.add_path_resolver("!first", ["a"], str)
65 #teach PyYAML that any untagged scalar with the path [a,b,c] has an implicit tag !second.
66 yaml
.add_path_resolver("!second", ["a", "b", "c"], str)
68 #teach PyYAML that any untagged plain scalar that looks like XdY has the implicit tag !dice.
69 for cls
in [Dice
, Foo
]:
70 yaml
.add_implicit_resolver(cls
.yaml_tag
, cls
.yaml_pattern
)
76 return yaml
.dump(foo
, default_flow_style
=False)
78 print "loading '2d6' turns into: ", load('2d6')
79 print "dumping Dice(2,6) looks like: ", dump(Dice(2,6))
80 print "loading foomoo: ", load('foomoo')
81 print "loading !foo bar: ", load('!foo bar')
82 print "dumping Foo(moo): ", dump(Foo("moo"))
83 print "loading a: moo ", load("a: moo")
84 print "loading a: b: c: input goes here", load("a:\n b:\n c: input goes here")