St.number_input with default value None?

Hello, this is my first question here :smiley:
Iโ€™m trying to have something like a st.number_input field with default value None unless somebody writes down an int value, is it possible?
Basically I need to call a seed for np.random.default_rng(seed) only if inputted by the user.
Thanks in advance!

Hello Alex, I encountered the same needs. However, as far as I know, Streamlit doesnโ€™t support number input with None yet.

In the end, I come out with two solutions:

  1. Use text_input and then sanitize the input. [Easy solution]
number = st.text_input('Number', value=None)
if number == 'None' or number == '':
    number = None
elif number.isdecimal():
    number = int(number)
    st.error('Input must be number')
  1. Inherit NumberInputMixin class and do the modification. [Hard solution]
    This is just some idea, Iโ€™m not really sure that this could work. But as far as I know, you could inherit NumberInputMixin (this is the class use to create number_input) and override the input_number method.
from streamlit.elements.number_input import NumberInputMixin

class NumberInputMixinNone(NumberInputMixin):
    def number_input(...):
        . . .

Anyway, if you found any better solution, please let me know. Thank you!

I would rather separate the two decisions:

  • Ask the user whether they want to specify a seed or nor.
  • Ask for the seed only when it is needed.
use_custom_seed = st.checkbox("Use custom seed")
seed = st.number_input("Custom seed", 0, label_visibility="collapsed", disabled=not use_custom_seed)
if not use_custom_seed:
    seed = None

st.metric("Seed", seed)
1 Like

Your solution is much better, thanks Goyo!