How about:
class Bunch(yaml.YAMLObject):
yaml_tag = u'!Bunch'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return '{c}({a})'.format(
c = self.__class__.__name__,
a = ', '.join(
['='.join(map(str,item)) for item in self.__dict__.items()]))
tag_names = ['define', 'action']
namespace = {}
for name in tag_names:
namespace[name] = type(name, (Bunch,), {'yaml_tag':u'!{n}'.format(n = name)})
definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
text = yaml.dump_all([namespace['define'](**definitions),
namespace['action'](**actions)],
default_flow_style = False,
explicit_start = True)
print(text)
which yields
--- !define
one: 1
three: 3
two: 2
--- !action
print: 'no'
report: maybe
run: 'yes'
And to load the YAML back into Python objects:
for item in yaml.load_all(text):
print(item)
# define(one=1, three=3, two=2)
# action(print=no, report=maybe, run=yes)
The subclasses of YAMLObject were used to create the application-specific tags.