import ast


def replace_fields(node, **kwds):
    """
    Return a node with several of its fields replaced by the given values.
    """
    new_kwds = dict(ast.iter_fields(node))
    for key, value in kwds.items():
        if value is not new_kwds[key]:
            break
    else:
        return node
    new_kwds.update(kwds)
    return type(node)(**new_kwds)