def diff_set(before, after, create_replaced=True):
    """Compare sets to get additions, removals and replacements

    Return 3 sets:
    added -- objects present in second set, but not present in first set
    removed -- objects present in first set, but not present in second set
    replaced -- objects that have the same name in both sets, but are different
    """
    removed = before - after
    added = after - before
    replaced = set()

    removed_by_name = {}
    for element_removed in removed:
        removed_by_name[element_removed.name] = element_removed
    for element_added in added:
        element_removed = removed_by_name.get(element_added.name)
        if element_removed and create_replaced:
            replaced.add((element_removed, element_added))
    if create_replaced:
        for (element_removed, element_added) in replaced:
            removed.discard(element_removed)
            added.discard(element_added)

    return (added, removed, replaced)