from typing import Mapping
import yaml
from typing import Iterable


def _infer_write(data, newline=False):
    """
    Infer function with which to write a data structure.

    :param str | Mapping | Iterable[str] data: the data to write to disk
    :param bool newline: whether to add newline to text lines
    :return function(object, file) -> object: function that writes data to
        a file stream, possibly returning a value
    """
    if isinstance(data, Mapping):

        def write(d, f):
            yaml.dump(d, f)

    else:
        make_line = (lambda l: l + "\n") if newline else (lambda l: l)
        if isinstance(data, str):

            def write(d, f):
                f.write(make_line(d))

        elif isinstance(data, Iterable):

            def write(d, f):
                for l in d:
                    f.write(make_line(l))

        else:
            raise TypeError("Unexpected data structure type: {}".format(type(data)))
    return write