Skip to content

Selectbox resets selection on visible name change #6352

@CHerSun

Description

@CHerSun

Checklist

  • I have searched the existing issues for similar issues.
  • I added a very descriptive title to this issue.
  • I have provided sufficient information below to help reproduce this issue.

Summary

If cosmetics fields of an object are modified (without touching the object or its key fields) - selectbox resets selection.

Reproducible Code Example

Open in Streamlit Cloud

import streamlit as st
from functools import partial

class A:
    def __init__(self, id: int, name: str):
        self.id = id
        self.name = name
    
    def __hash__(self) -> int:
        return hash(self.name)
    def __eq__(self, other) -> bool:
        return (self.id == other.id) if str(type(self)) == str(type(other)) else False 
    
def on_change(index: int) -> None:
    new_name = st.session_state["new_name"]
    st.session_state["lst"][index].name = new_name

# Init state
if not "lst" in st.session_state:
    st.session_state["lst"] = [A(1, "one"), A(2, "two"), A(3, "three")]

# Fetch state
lst = st.session_state["lst"]

# Let user pick what to edit and if anything selected - show a field to change name
selected = st.selectbox("Select item", [""]+lst, format_func=lambda a: f"#{a.id} {a.name}" if a else "")
if selected:
    index = lst.index(selected)
    st.text_input("New name", selected.name, key="new_name", on_change=partial(on_change, index))

Steps To Reproduce

Run above example.
Select any object.
Modify name and press ctrl+enter.
See that selection resets to the very first item (index=0)

Expected Behavior

If object is the same object - its selection should be kept intact. I.e. index not by visible name, but rather by object equality + hash.

I didn't check, but if key field is hidden - I guess this could cause incorrect object selection actually.

Current Behavior

Is this a regression?

  • Yes, this used to work in a previous version.

Debug info

  • Streamlit version: 1.20.0
  • Python version: 3.11.2
  • Operating System: Windows 10
  • Browser: Firefox latest
  • Virtual environment: venv

Additional Information

Are you willing to submit a PR?

  • Yes, I am willing to submit a PR!

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature:st.selectboxRelated to the `st.selectbox` widgettype:enhancementRequests for feature enhancements or new features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions