Share the selectbox output across scripts

Hi,
I have a question regarding the good practice to separate the data manipulation and layout. The code could be long and messy to have data manipulation, HTML components, CSS, streamlit widgets altogether.

According to my understanding:

  1. It’s possible to write the HTML in a separate file and import it into the layout file.
  2. It’s possible to write the normal CSS, and import and use it with markdown.
  3. It’s possible to share a global variable across the files that I can put data manipulation into another file.
  4. It’s possible to write functions separately in another file.

The question is that how could I share the output from selectbox across two or multiple scripts?

For example, I want to get the selected_country from app.py, send it to the data.py. Finally, render the data with st.text (pseudo code):

[app.py]

import data
import streamlit as st

selected_country = st.selectbox('', data.countries, index=data.countries.index('Taiwan')) # send to data.py
st.text(f"{selected_country} vaccination rate is: {data.country_vaccination}%")

[data.py]

countries = df_vaccination_by_country.sort_values(by='location')['location'].tolist()

country_vaccination = df_vaccination_by_country\
                      [df_vaccination_by_country['location']==selected_country]\
                      ['total_vaccinations_per_hundred'].values[0]

Hi Woden,

I’m not sure if this is what you’re looking for but I’ve made a (hopefully super simple) example that changes the value of the selected country in a different script:
(both of these scripts need to be in the same directory)

app.py

import streamlit as st
from data import Data

your_data_object = Data()
selected_country = st.selectbox('', ["Canada", "Germany", "Taiwan"])
returned_country = your_data_object.do_something(selected_country)
st.text(returned_country)

data.py

class Data:

    def do_something(self, country):
        print("Your selected country: ", country)
        # Changing country value to show changing data works in app.py
        if country == "Canada":
            country = "Netherlands"
        if country == "Germany":
            country = "France"
        if country == "Taiwan":
            country = "Belarus"
        return country

Let me know if this was the answer you needed :slight_smile:

Understood! Thank you @Fhireman , the data is wrapped into an object, and the method inside the class returns the query results to the app.py to render.

I’ve accepted the answer, and thank you for helping.
Sincerely,

1 Like