def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,
            **kwargs):
    """
    Serialize a Python object into a YAML stream with OrderedDict and
    default_flow_style defaulted to False.

    If stream is None, return the produced string instead.

    OrderedDict reference: http://stackoverflow.com/a/21912744
    default_flow_style reference: http://stackoverflow.com/a/18210750

    :param data: python object to be serialized
    :param stream: to be serialized to
    :param Dumper: base Dumper class to extend.
    :param kwargs: arguments to pass to to_dict
    :return: stream if provided, string if stream is None
    """

    class OrderedDumper(dumper_cls):
        pass

    def dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())

    OrderedDumper.add_representer(OrderedDict, dict_representer)

    obj_dict = to_dict(obj, **kwargs)

    return yaml.dump(obj_dict, stream, OrderedDumper,
                     default_flow_style=default_flow_style)
def to_yaml ( obj , stream = None , dumper_cls = yaml . Dumper , default_flow_style = False , ** kwargs ) : class OrderedDumper ( dumper_cls ) : pass def dict_representer ( dumper , data ) : return dumper . represent_mapping ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , data . items ( ) ) OrderedDumper . add_representer ( OrderedDict , dict_representer ) obj_dict = to_dict ( obj , ** kwargs ) return yaml . dump ( obj_dict , stream , OrderedDumper , default_flow_style = default_flow_style )
Serialize a Python object into a YAML stream with OrderedDict and
    default_flow_style defaulted to False.

    If stream is None, return the produced string instead.

    OrderedDict reference: http://stackoverflow.com/a/21912744
    default_flow_style reference: http://stackoverflow.com/a/18210750

    :param data: python object to be serialized
    :param stream: to be serialized to
    :param Dumper: base Dumper class to extend.
    :param kwargs: arguments to pass to to_dict
    :return: stream if provided, string if stream is None