Hi, I have a problem using the unique key in streamlit function, for instance, st.selectbox(*args, key='key', **kwargs)
.
For my own purpose, I find it annoying to specify the key every time in the code. So, I decided to write a decorator function which automatically assign a random key to each of the selectbox. Here is my code:
class StreamlitWrapper:
@staticmethod
def _rdnkey_decorator(func):
def wrapper(*args, **kwargs):
# generate a key with 10 characters
# rdn_key = rdnkey_generator.generate()
rdn_key = ''.join([random.choice(string.ascii_letters) for _ in range(10)])
kw = dict(
key = rdn_key,
)
kw.update(kwargs)
return func(*args, **kw)
return wrapper
Then, I defined an inherited class
class MyClass(StreamlitWrapper):
@StreamlitWrapper._rdnkey_decorator
def selection(self, label='selection', **kwargs):
return st.selectbox(label, **kwargs)
and used it in my application code. For example,
myclass = MyClass()
choice1 = myclass.selection()
choice2 = myclass.selection()
The above code gives the the “unique key error”, i.e.
"When a widget is created, it’s assigned an internal key based on
its structure. Multiple widgets with an identical structure will
result in the same internal key, which causes this error.
To fix this error, please pass a unique key
argument to
st.selectbox
." However, if I pass the key in the application code,
myclass = MyClass()
choice1 = myclass.selection()
choice2 = myclass.selection(key='no-problem') # Note here the key is updated by the random key.
It works perfectly fine. Do anyone have some idea what went wrong here?
Thanks a lot.