Switch_page function execute twice the code

Can someone confirm that when the switch_page function is called, all the code of the page I’m supposed to leave is re-executed once?
Little snippet as example [I’ve launched streamlit from conda terminal]

In Page1:
print(“Test”)
button = st.button(“Go to page 2”)
if button:
___switch_page(“Page2”)

The page is correctly changed but in my conda terminal I’m seeing “Test” printed twice.

Thank you.

Regards,
Lorenzo

As written, page 1 will reload and then the redirect to page 2 will trigger. The value of the variable button is false when page 1 first loads (redirect not triggered). When you click, since you have no callback function, page 1 will immediately reload, this time assigning true to button at which point you enter the conditional and trigger the redirect.

May you know how to avoid this effect? Anyway thank you for the punctual clarification.

Little forgotten note: Switch_page function taken from the Streamlit-extras library

Can you use a callback function instead?

def do_a_thing():
    # do a thing

st.button('Do A Thing', on_click=do_a_thing)

Or if you want to pass it the switch_page function directly:

st.button('Go to Page 2', on_click=switch_page, args=('Page2',))

When you interact with a widget, the callback function will run before reloading the page. I haven’t used the extras library, so I’m not sure how the page switching is implemented and if there would be a need to step around things more delicately. If the above doesn’t work, then you can put the logic to switch pages at the beginning of your script, pulling the button value from session_state directly if you need to.

Thank you so much for the advices. Unfortunately the callback it’s not working because it’s in conflict with the extras library. But the idea was great.

As workaround at the end I’ve implemented something similar but more code-related. I have a pandas profile call that is quite time-consuming, so by a session state flag I’m avoiding executing it the second time so even if the page is rerun the side-effect is invisible.

Anyway I found this quite annoying. I’ve another page quite “heavy” and full of functions and calls with some checkboxes, every time a checkbox is clicked (they’re supposed to be clicked and unclicked oftenly) all the page is always refreshed. I can get the logic of the reason, but it’s limiting a lot the powerful of this library. Sorry for the outburst though…

Thank you again.

Are you using caching and forms where appropriate to optimize reloading?

Also, what conflict are you getting with the library?