import six


def ensure_str(name, value, allow_none=False):
    """Raise an error if value is not a str and, optionally, is None."""
    if value is None and allow_none:
        return value

    if not isinstance(value, six.text_type):
        raise TypeError("{} must be str: {}".format(name, value))
    return value