Streamlit Code Editor
Streamlit Code Editor is an active, community-driven component that integrates a React-Ace based code editor into Streamlit applications. It currently stands at version 0.1.22, offering features like custom themes, syntax highlighting for various languages, and customizable interface elements. The library maintains an active release cadence, with updates addressing performance, bug fixes, and new features.
Common errors
-
Editor content does not reflect changes to the initial code string on subsequent reruns.
cause The `code_editor` component, when given a static `key`, defaults `allow_reset` to `False`, preventing programmatic updates to its displayed content from the input `code` argument.fixPass `allow_reset=True` to the `code_editor` function: `code_editor(initial_code, key='my_editor', allow_reset=True)`. -
The first edit made to the code editor is not registered or reverts to the original value.
cause This often occurs due to Streamlit's rerun model and how `st.session_state` is updated from widget outputs, similar to the 'double submit' problem in Streamlit's `st.data_editor`.fixEnsure `st.session_state` is correctly initialized for any variable managing the editor's content. When reacting to the editor's output, use `response_dict['id']` to confirm a *new* response before processing and updating state, preventing reprocessing of stale values. -
Buttons or callbacks intended to modify the editor's content do not work on the first click or behave inconsistently.
cause Incorrect management of `st.session_state` when trying to programmatically change the `code_editor`'s value via a button click or callback.fixEnsure `st.session_state` variables are properly initialized and updated within callback functions or directly within the main script logic based on user interaction, then passed to the `code_editor` with `allow_reset=True`.
Warnings
- gotcha Editor content may not update when input code changes if `key` is static and `allow_reset` is `False`.
- gotcha The default `response_mode` only returns content on explicit user commands (e.g., Ctrl+Enter).
- gotcha Streamlit's rerun model can lead to unexpected widget behavior or lost input if `st.session_state` is not handled correctly with interactive components.
Install
-
pip install streamlit-code-editor
Imports
- code_editor
from code_editor import code_editor
Quickstart
import streamlit as st
from code_editor import code_editor
def main():
st.set_page_config(layout="wide")
st.title("My Streamlit Code Editor App")
initial_code = """import pandas as pd
def greet(name):
return f"Hello, {name}!"
print(greet("Streamlit"))
"""
st.subheader("Edit your Python code:")
response_dict = code_editor(initial_code, lang="python", key="my_editor")
if response_dict and response_dict["type"] == "submit":
st.write("You submitted the following code:")
st.code(response_dict["text"], language="python")
if __name__ == "__main__":
main()