Skip to content

Widgets are not unique when stored in a dict in sub-class #2944

Closed
@aidanheerdegen

Description

@aidanheerdegen

This may be a python feature rather than an ipywidgets bug, but thought it was worth pointing out in case someone else has a similar issue and can't figure it out.

I am subclassing HBox and VBox to create self-contained "combo-widgets". However, I noticed that when I made independent instances of my combo-widgets, the widgets they contained seemed to be connected. It turns out that because I was storing the widgets in a dict the widgets were pointing to the same address.

Here is an MCVE:

import ipywidgets as widgets
class myBox(widgets.HBox):
    def __init__(self):
        self.widgets['innerbox']=widgets.Text()
        super().__init__(children=[self.widgets['innerbox']])
b1 = myBox()
print(id(b1.widgets['innerbox']))
b2 = myBox()
print(id(b1.widgets['innerbox']), id(b2.widgets['innerbox']))

Result is

140583624309712
140583623982352 140583623982352

It doesn't happen if I store the inner widget like so

        self.innerbox=widgets.Text()

if I give the inner widgets different arguments every time they are instantiated they still end up pointing to the same place

import ipywidgets as widgets
import uuid
class myBox(widgets.HBox):
    def __init__(self):
        self.id = str(uuid.uuid1())
        self.widgets['innerbox']=widgets.Text(description=str(self.id))
        super().__init__(children=[self.widgets['innerbox']])
b1 = myBox()
print(b1.id, b1.widgets['innerbox'])
b2 = myBox()
print(b2.id, b2.widgets['innerbox'])
print(b1.id, b1.widgets['innerbox'])
print(id(b1.widgets['innerbox']), id(b2.widgets['innerbox']))
dfa1e66c-d865-11ea-bd85-fa163e8ac59c Text(value='', description='dfa1e66c-d865-11ea-bd85-fa163e8ac59c')
dfa587f4-d865-11ea-a034-fa163e8ac59c Text(value='', description='dfa587f4-d865-11ea-a034-fa163e8ac59c')
dfa1e66c-d865-11ea-bd85-fa163e8ac59c Text(value='', description='dfa587f4-d865-11ea-a034-fa163e8ac59c')
140583624267536 140583624267536

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions