def safe_str(s):
    """
    Accepts a bytes or str and returns a str. Weechat will return str types
    unless the string is not valid utf-8, in which case it returns bytes. In
    this case we just fall back to latin1, which is guaranteed to work.
    """
    if isinstance(s, str):
        return s
    elif isinstance(s, bytes):
        return s.decode('latin1')
    raise TypeError("unknown string type {0}".format(type(s)))