import logging
import traceback

logger = logging.getLogger("replace_widget")


def replace_widget(parent, name, new, delete=False):
    old = getattr(parent, name)
    if old is new:
        logger.warning(f"\n{''.join(traceback.format_stack())}\nyou are trying to replace {old!r} with itself.")
        return
    if old.parentWidget().layout().replaceWidget(old, new) is None:
        raise AssertionError(f"{name} not found, cannot replace it.")
    old.hide()
    setattr(parent, name, new)
    new.show()
    if delete:
        old.deleteLater()
        del old
