Sidebar disappearing when import

For example I have such a project structure:

projectName/

  • main.py

  • sidebar.py

In sidebar.py I have a class:

from streamlit import sidebar
class Sidebar:
    header = sidebar.header('')
    some_input = sidebar.text_input('input', value=0)
    some_radio = sidebar.radio('radio', ['choice_1','choice_2'])

Code in main.py:

import streamlit as st
from sidebar import Sidebar
if __name__ == '__main__':
    sb =  Sidebar()
    header = st.header("Main header")

Next I run my app: streamlit run main.py

Now I go to the web page and see the sidebar and header. But if I switch the radio button, the sidebar disappears.

Hello @VolDr, welcome to the forum!

This is because imports are run once. And in your case, the body of your Sidebar class is executed when sidebar.py is parsed, or in other word when you do from sidebar import Sidebar.

You can verify this by removing the line sb = Sidebar() and running your app again. Your sidebar should still appear on the first run.

To fix your issue, what you want to do is this instead:

# sidebar.py
from streamlit import sidebar

class Sidebar:
    def __init__(self):
        header = sidebar.header('')
        some_input = sidebar.text_input('input', value=0)
        some_radio = sidebar.radio('radio', ['choice_1','choice_2'])

That __init__() function will be executed when you do sb = Sidebar().

2 Likes