i have display_test_scenarios which displays a streamlit widget that allows the user to select test scenarios. this function is tightly coupled with session_state and main function. how can i remove these coupling from the function?
...
def display_test_scenarios():
stc.markdown("Test scenarios", font_size="25px", font_weight="bold")
with st.container(height=400, border=False):
selected_scenarios = stc.multiselect(
title="select test cases",
options=st.session_state.app.test_cases,
default=st.session_state.app.selected_scenarios,
)
codes_button = stc.st_button("Generate test codes", "codes_button", "right")
if codes_button:
st.session_state.app.update(selected_scenarios=selected_scenarios)
with stc.LottieAnimation("assets/Animation-1724036221793.json", "Generating Code"):
st.session_state.app.generate_results(step="code_generation")
st.rerun()
def main():
code
Assistant
User
st.rerun() is required to display the updated ui, how to solve this issue
Assistant
if "app" not in st.session_state:
st.session_state.app = AppManager()
inputs_col, scenarios_col = st.columns(2, gap="large", vertical_alignment="top")
with inputs_col:
repo_url_col, lanuage_col = st.columns([0.7, 0.3], gap="small")
repo_url = repo_url_col.text_input("Enter BitBucket repo link here:", value=st.session_state.app.repo_url)
language = lanuage_col.selectbox("Language", options=["Python", "Java"], index=0)
repo_cloned = handle_repo_url(repo_url)
file_selection_col, method_selection_col = st.columns([0.5, 0.5], gap="small")
if repo_cloned:
repo_tree_data = make_repo_tree_structure(st.session_state.app.repo_path)
disabled_treeview = False
search_visible = True
else:
repo_tree_data = []
disabled_treeview = True
search_visible = False
with file_selection_col:
stc.markdown(
"Select the file you want to test :", font_size="14px", font_color="#454545"
)
file_path = st_ant_tree(
treeData=repo_tree_data,
key="file_select",
multiple=False,
placeholder="Choose a File",
showSearch=search_visible,
treeCheckable=False,
disabled=disabled_treeview,
)
if file_path is not None:
file_name, packages, complete_methods = handle_file_path (file_path)
if file_path and not disabled_treeview:
function_tree_data = transform_module_to_tree(st.session_state.app.complete_methods)
disabled_treeview = False
search_visible = True
else:
function_tree_data = []
disabled_treeview = True
search_visible = False
with method_selection_col:
stc.markdown(
"Select the method/function you want to test:", font_size="14px", font_color="#454545",
)
method_name = st_ant_tree(
treeData=function_tree_data,
key="method_name",
multiple=False,
placeholder="Choose a method/function",
showSearch=search_visible,
treeCheckable=False,
disabled=disabled_treeview,
)
handle_method_name(method_name)
objective = st.text_area("Provide additional info of the method (optional)")
sample_data = st.text_area("Provide sample data for the method (optional)")
st.session_state.app.update(objective=objective, sample_data=sample_data)
scenario_button = stc.st_button("Generate Test Scenarios", "scenario_button")
components = st.session_state.app.components
if len(components) == 0:
if scenario_button:
with scenarios_col:
start_code_generation()
elif components[-1] == "verify_io_user_input":
with scenarios_col:
display_chat_interface(components)
elif components[-1] == "user_input":
with scenarios_col:
display_chat_interface(components)
elif "scenarios_section" in components:
with scenarios_col:
display_test_scenarios()
if "code_section" in components:
display_code()
if "results_section" in components :
display_results()
if name == "main":
main()
def display_test_scenarios(data):
stc.markdown("Test scenarios", font_size="25px", font_weight="bold")
with st.container(height=400, border=False):
selected_scenarios = stc.multiselect(
title="select test cases",
options=data.test_cases,
default=data.selected_scenarios,
)
codes_button = stc.st_button("Generate test codes", "codes_button", "right")
if codes_button:
data.update(selected_scenarios=selected_scenarios)
with stc.LottieAnimation("assets/Animation-1724036221793.json", "Generating Code"):
data.generate_results(step="code_generation")
return data
To decouple the display_test_scenarios function from the session_state and main, you can modify the function to accept a contextual object that contains all the relevant data and methods required for its execution. This way, you can isolate the logic of the function and make it reusable. Below is an approach to achieve that:
Create a standalone class to handle data: Instead of directly using st.session_state.app, you pass an instance of a class that holds the necessary data and methods.
Modify the display_test_scenarios function: Change the function to accept an object of that class, which includes the states you need.
def display_test_scenarios(data: TestScenarioData):
stc.markdown("Test scenarios", font_size="25px", font_weight="bold")
with st.container(height=400, border=False):
selected_scenarios = stc.multiselect(
title="Select test cases",
options=data.test_cases,
default=data.selected_scenarios,
)
codes_button = stc.st_button("Generate test codes", "codes_button", "right")
if codes_button:
data.update(selected_scenarios)
with stc.LottieAnimation("assets/Animation-1724036221793.json", "Generating Code"):
data.generate_results(step="code_generation")
return data
3. Update the main function to pass the necessary data:
python
def main():
if "app" not in st.session_state:
st.session_state.app = AppManager()
inputs_col, scenarios_col = st.columns(2, gap="large", vertical_alignment="top")
# ... [existing code] ...
# Create an instance of TestScenarioData to pass to the function
scenario_data = TestScenarioData(
test_cases=st.session_state.app.test_cases,
selected_scenarios=st.session_state.app.selected_scenarios,
update_method=st.session_state.app.update,
generate_results_method=st.session_state.app.generate_results
)
if "scenarios_section" in st.session_state.app.components:
with scenarios_col:
display_test_scenarios(scenario_data)
# ... [existing code] ...
Benefits of Refactoring
Separation of Concerns: The display_test_scenarios function no longer needs to know about st.session_state or how the rest of the application is structured. It focuses solely on displaying scenarios and handling user input.
Reusable Code: You can reuse the display_test_scenarios function in other parts of your application, or in different contexts simply by passing the appropriate data object.
Easier Testing: You can write unit tests for display_test_scenarios with a mock object representing the TestScenarioData, making it easier to test the function independently.
This pattern also allows for easier updates in the future, as you can modify the data structure without changing the function's internal logic.
In Streamlit, the st.rerun() function is often used to refresh the UI state and display updates in response to user actions. However, relying on st.rerun() can lead to code that is harder to manage and less efficient, especially if the rerun is not strictly necessary.
To solve the issue of needing to display updated UI components without relying on st.rerun(), you can consider the following approaches:
1. Use st.session_state Explicitly
Instead of performing a rerun to update the UI, you can manipulate st.session_state directly. You can set flags or variables in session_state to handle visibility and state management. Here's how you can implement it:
Updated display_test_scenarios function:
python
def display_test_scenarios(data: TestScenarioData):
stc.markdown("Test scenarios", font_size="25px", font_weight="bold")
with st.container(height=400, border=False):
selected_scenarios = stc.multiselect(
title="Select test cases",
options=data.test_cases,
default=data.selected_scenarios,
)
codes_button = stc.st_button("Generate test codes", "codes_button", "right")
if codes_button:
data.update(selected_scenarios)
with stc.LottieAnimation("assets/Animation-1724036221793.json", "Generating Code"):
data.generate_results(step="code_generation")
# Instead of calling rerun, we update a session state flag
st.session_state.app.show_code_section = True
2. Managing Component State in main
In your main function, you can read from the session_state to determine what to display next, without needing to rerun the entire app:
python
def main():
if "app" not in st.session_state:
st.session_state.app = AppManager()
# Initialize a flag for section visibility if not present
if "show_code_section" not in st.session_state.app:
st.session_state.app.show_code_section = False
inputs_col, scenarios_col = st.columns(2, gap="large", vertical_alignment="top")
# ... [existing input handling code] ...
# Pass the scenario data to the function
scenario_data = TestScenarioData(
test_cases=st.session_state.app.test_cases,
selected_scenarios=st.session_state.app.selected_scenarios,
update_method=st.session_state.app.update,
generate_results_method=st.session_state.app.generate_results
)
if "scenarios_section" in st.session_state.app.components:
with scenarios_col:
display_test_scenarios(scenario_data)
# Check if we need to show the code section based on session state
if st.session_state.app.show_code_section:
display_code()
# Continue with other displays such as results
# ... [additional display logic] ...
3. Alternative: Use Callbacks Carefully
For more modular applications, Streamlit provides a mechanism to handle callbacks more efficiently. You can wrap your UI component logic in a function that updates specific session_state states, avoiding the need to rerun. However, this may require deeper restructuring of your codebase.
General Guidance:
Minimize Rerun Usage: Use rerun sparingly. Instead, manage state effectively with session_state and conditionally render UI components based on this state.
Component/Dynamic UI Visibility: By tracking visibility directly in session_state, you can conditionally render components without reruns.
Update logic: Ensure that your logic for updating component states is encapsulated cleanly to maintain clean and readable code.
By following these principles, you can ensure that your Streamlit application behaves responsively and efficiently without the constant need to rerun.