Skip to content

Container del child_widget doesn't check if widget has already been removed. #739

Description

@Antyos

Describe the bug
Calling del widget on a widget that has already been removed will raise a ValueError.

To Reproduce

from magicgui import widgets


class DeleteTest(widgets.Container):
    def __init__(self, x: int):
        self.x = x
        self.label = widgets.Label(value=f"x = {x}")
        self.delete_button = widgets.PushButton(text="Delete me")
        self.delete_button.clicked.connect(self.delete_label)
        super().__init__(widgets=[self.label, self.delete_button])

    def delete_label(self):
        self.remove(self.label)
        # Now, I don't want the label reference around anymore
        del self.label  # Internally calls self.remove(), but the item is already gone, so it errors


DeleteTest(x=5).show(run=True)

Or even:

d = DeleteTest(x=5)
# x was never a child widget, but this should still be valid
del d.x  # raises ValueError

I think the issue is related to these lines here:

def remove(self, value: Widget | str) -> None:
"""Remove a widget instance (may also be string name of widget)."""
super().remove(value) # type: ignore
def __delattr__(self, name: str) -> None:
"""Delete a widget by name."""
self.remove(name)

Expected behavior
Normal behavior for deling a variable in a mutable sequence after it has been removed does not raise an error.

x = 5
mutable_seq = [1, 2, x]
mutable_seq.remove(x)
# mutable_seq.remove(x)  # Would raise an error if you tried to remove it again.
del x  # But this is fine

print(f"mutable_seq: {mutable_seq}")

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • OS: Windows, Python 3.13.9
  • backend: PyQt6==6.9.1
  • magicgui version 0.10.3.dev3+g2d985e7a4

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions