How to update table.columns correctly? #4418
-
QuestionHi everyone. I am trying to update from nicegui import ui
class Headers:
doc = [
{"name": "task", "label": "Task", "field": "task"},
{"name": "doc", "label": "Doc", "field": "doc"},
]
no_doc = [{"name": "task", "label": "Task"}]
rows = [{"task": "Task 1", "doc": "Some Docs"}, {"task": "Task 2"}]
ui.checkbox("Show Doc").on_value_change(lambda v: on_checkbox_change(v.value))
table = ui.table(columns=Headers.doc, rows=rows, row_key="task", selection="multiple")
def on_checkbox_change(show: bool):
if show:
table.columns = Headers.doc
else:
table.columns = Headers.no_doc
print(Headers.doc)
print(Headers.no_doc)
print(Headers.doc == Headers.no_doc)
ui.run() After I clicked the checkbox three times, I found that the value of class Headers was changed. I'm not sure how to describe this problem in words, I hope you can run my code above and then you will understand what I mean. I don't know if this is a bug. If there is another correct way, please tell me. Thank you very much. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
BTW I used Python 3.12.7 to run my code.Could this be the cause of the problem? |
Beta Was this translation helpful? Give feedback.
-
Hi @weinibuliu, This is indeed unexpected. I guess the problem is that Minimum reproduction: a = [{"name": "a", "label": "A", "field": "a"}]
b = [{"name": "b", "label": "B", "field": "b"}]
table = ui.table(columns=a, rows=[{"a": "A1", "b": "B1"}, {"a": "A2", "b": "B2"}])
ui.checkbox("Toggle", on_change=lambda v: toggle(v.value))
def toggle(show_b: bool):
table.columns = b if show_b else a A quick solution is to pass a copy of the original columns like this: table = ui.table(columns=a[:], rows=[{"a": "A1", "b": "B1"}, {"a": "A2", "b": "B2"}]) But we have to think about the reasons why |
Beta Was this translation helpful? Give feedback.
Hi @weinibuliu,
This is indeed unexpected. I guess the problem is that
ui.table(columns=a, ...)
keeps a reference ona
. When writing to the property liketable.columns = b
, the content of the original reference is overwritten byb
.Minimum reproduction:
A quick solution is to pass a copy of the original columns like this: