Skip to content

Commit

Permalink
Remove st._is_running_with_streamlit (streamlit#5481)
Browse files Browse the repository at this point in the history
We currently use a "private" flag in Streamlit's `__init__.py` (scare quotes around "private" because it's actually accessed everywhere), called `_is_running_with_streamlit`, to test whether a Streamlit app was started via `streamlit run app.py` (`_is_running_with_streamlit=True`) or in "raw mode" via `python app.py` (`_is_running_with_streamlit=False`).

This is unfortunate for a number of reasons: 
- it means lots of code must do `import streamlit` (which can lead to circular import errors)
- it requires that we manually set the flag at the right times, even though we have other signals about whether Streamlit is actually running
- and it's just weird to have a private flag accessed so very publicly

But now that `streamlit.Runtime` is a singleton, we can ditch this flag and instead just check if the Runtime singleton exists or not!

This PR:
- Adds the `Runtime.exists()` class method, which returns True if the Runtime singleton exists
- Also adds the convenience function `runtime.exists()` directly in the `runtime` package
- Replaces all usage of `st._is_running_with_streamlit` with `runtime.exists()`
  • Loading branch information
tconkling authored Oct 5, 2022
1 parent effc61f commit adde74a
Show file tree
Hide file tree
Showing 47 changed files with 133 additions and 126 deletions.
3 changes: 2 additions & 1 deletion e2e/scripts/linked_sliders.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

if st._is_running_with_streamlit:
if runtime.exists():

to_celsius = lambda fahrenheit: (fahrenheit - 32) * 5.0 / 9.0
to_fahrenheit = lambda celsius: 9.0 / 5.0 * celsius + 32
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/redisplayed_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

if st._is_running_with_streamlit:
if runtime.exists():

if st.checkbox("checkbox 1"):
if st.checkbox("checkbox 2"):
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/session_state_frontend_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

if st._is_running_with_streamlit:
if runtime.exists():
if "checkbox1" not in st.session_state:
st.session_state.checkbox1 = True

Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_button.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

# st.session_state can only be used in streamlit
if st._is_running_with_streamlit:
if runtime.exists():

def on_click(x, y):
if "click_count" not in st.session_state:
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_checkbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

i1 = st.checkbox("checkbox 1", True)
st.write("value 1:", i1)
Expand All @@ -23,7 +24,7 @@
i3 = st.checkbox("checkbox 3")
st.write("value 3:", i3)

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.checkbox_clicked = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_date_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from datetime import date, datetime

import streamlit as st
from streamlit import runtime

d1 = st.date_input("Single date", date(1970, 1, 1), min_value=date(1970, 1, 1))
st.write("Value 1:", d1)
Expand Down Expand Up @@ -44,7 +45,7 @@
)
st.write("Value 8:", d8)

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.date_input_changed = True
Expand Down
15 changes: 8 additions & 7 deletions e2e/scripts/st_file_uploader.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,19 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

single_file = st.file_uploader("Drop a file:", type=["txt"], key="single")
if single_file is None:
st.text("No upload")
else:
st.text(single_file.read())

# Here and throughout this file, we use if st._is_running_with_streamlit:
# Here and throughout this file, we use `if runtime.is_running():`
# since we also run e2e python files in "bare Python mode" as part of our
# Python tests, and this doesn't work in that circumstance
# st.session_state can only be accessed while running with streamlit
if st._is_running_with_streamlit:
if runtime.exists():
st.write(repr(st.session_state.single) == repr(single_file))

disabled = st.file_uploader(
Expand All @@ -35,7 +36,7 @@
else:
st.text(disabled.read())

if st._is_running_with_streamlit:
if runtime.exists():
st.write(repr(st.session_state.disabled) == repr(disabled))

multiple_files = st.file_uploader(
Expand All @@ -50,7 +51,7 @@
files = [file.read().decode() for file in multiple_files]
st.text("\n".join(files))

if st._is_running_with_streamlit:
if runtime.exists():
st.write(repr(st.session_state.multiple) == repr(multiple_files))

with st.form("foo"):
Expand All @@ -73,7 +74,7 @@
else:
st.text(hidden_label.read())

if st._is_running_with_streamlit:
if runtime.exists():
st.write(repr(st.session_state.hidden_label) == repr(hidden_label))

collapsed_label = st.file_uploader(
Expand All @@ -87,10 +88,10 @@
else:
st.text(collapsed_label.read())

if st._is_running_with_streamlit:
if runtime.exists():
st.write(repr(st.session_state.collapsed_label) == repr(collapsed_label))

if st._is_running_with_streamlit:
if runtime.exists():
if not st.session_state.get("counter"):
st.session_state["counter"] = 0

Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_multiselect.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from typing import Any, List

import streamlit as st
from streamlit import runtime


def set_multiselect_9_to_have_bad_state():
Expand Down Expand Up @@ -70,7 +71,7 @@ def set_multiselect_9_to_have_bad_state():
st.text(f"value 10: {i10}")
submitted = st.form_submit_button("Submit")

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.multiselect_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_number_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

i1 = st.number_input("number input 1")
st.write('value 1: "', i1, '"')
Expand All @@ -38,7 +39,7 @@
i8 = st.number_input("number input 8", label_visibility="collapsed")
st.write('value 8: "', i8, '"')

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.number_input_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_radio.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import pandas as pd

import streamlit as st
from streamlit import runtime

options = ("female", "male")
i1 = st.radio("radio 1", options, 1)
Expand Down Expand Up @@ -42,7 +43,7 @@
st.write("value 8:", i8)


if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.radio_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_select_slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import pandas as pd

import streamlit as st
from streamlit import runtime

w1 = st.select_slider(
"Label 1",
Expand Down Expand Up @@ -74,7 +75,7 @@

st.write("Value 7:", w7)

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.select_slider_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_selectbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

options = ("male", "female")
i1 = st.selectbox("selectbox 1", options, 1)
Expand Down Expand Up @@ -50,7 +51,7 @@
i7 = st.selectbox("selectbox 7", options, label_visibility="collapsed")
st.write("value 7:", i7)

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.selectbox_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_session_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

# st.session_state can only be accessed while running with streamlit
if st._is_running_with_streamlit:
if runtime.exists():
if "initialized" not in st.session_state:
st.session_state["item_counter"] = 0
st.session_state.attr_counter = 0
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

s1 = st.sidebar.slider("Label A", 0, 12345678, 12345678)
st.sidebar.write("Value A:", s1)
Expand Down Expand Up @@ -45,7 +46,7 @@
w6 = st.slider("Label 6", 0, 100, 36, label_visibility="collapsed")
st.write("Value 6:", w6)

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.slider_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_stop.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

st.text("Text before stop")

# Since st.stop() throws an intentional exception, we want this to run
# only in streamlit
if st._is_running_with_streamlit:
if runtime.exists():
st.stop()

st.text("Text after stop")
3 changes: 2 additions & 1 deletion e2e/scripts/st_text_area.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

i1 = st.text_area("text area 1")
st.write('value 1: "', i1, '"')
Expand Down Expand Up @@ -41,7 +42,7 @@
i9 = st.text_area("text area 9", "default text", label_visibility="collapsed")
st.write('value 9: "', i9, '"')

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.text_area_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_text_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import streamlit as st
from streamlit import runtime

i1 = st.text_input("text input 1")
st.write('value 1: "', i1, '"')
Expand All @@ -38,7 +39,7 @@
i8 = st.text_input("text input 8", "default text", label_visibility="collapsed")
st.write('value 8: "', i8, '"')

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.text_input_changed = True
Expand Down
3 changes: 2 additions & 1 deletion e2e/scripts/st_time_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from datetime import datetime, time

import streamlit as st
from streamlit import runtime

w1 = st.time_input("Label 1", time(8, 45))
st.write("Value 1:", w1)
Expand All @@ -31,7 +32,7 @@
w5 = st.time_input("Label 5", time(8, 45), label_visibility="collapsed")
st.write("Value 5:", w5)

if st._is_running_with_streamlit:
if runtime.exists():

def on_change():
st.session_state.time_input_changed = True
Expand Down
8 changes: 2 additions & 6 deletions lib/streamlit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,6 @@

cache = _gather_metrics(_cache)

# This is set to True inside cli._main_run(), and is False otherwise.
# If False, we should assume that DeltaGenerator functions are effectively
# no-ops, and adapt gracefully.
_is_running_with_streamlit: bool = False


def _update_logger() -> None:
_logger.set_log_level(_config.get_option("logger.level").upper())
Expand Down Expand Up @@ -476,6 +471,7 @@ def _maybe_print_use_warning() -> None:
The warning is printed only once.
"""
global _use_warning_has_been_displayed
from streamlit import runtime

if not _use_warning_has_been_displayed:
_use_warning_has_been_displayed = True
Expand All @@ -487,7 +483,7 @@ def _maybe_print_use_warning() -> None:
f"\n {warning} to view a Streamlit app on a browser, use Streamlit in a file and\n run it with the following command:\n\n streamlit run [FILE_NAME] [ARGUMENTS]"
)

elif not _is_running_with_streamlit and _config.get_option(
elif not runtime.exists() and _config.get_option(
"global.showWarningOnDirectExecution"
):
script_name = _sys.argv[0]
Expand Down
5 changes: 2 additions & 3 deletions lib/streamlit/elements/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

from typing_extensions import Final

import streamlit
from streamlit import runtime
from streamlit.elements.form import current_form_id, is_in_form
from streamlit.elements.utils import check_callback_rules, check_session_state_rules
Expand Down Expand Up @@ -328,7 +327,7 @@ def _button(
# every form). We throw an error to warn the user about this.
# We omit this check for scripts running outside streamlit, because
# they will have no script_run_ctx.
if streamlit._is_running_with_streamlit:
if runtime.exists():
if is_in_form(self.dg) and not is_form_submitter:
raise StreamlitAPIException(
f"`st.button()` can't be used in an `st.form()`.{FORM_DOCS_INFO}"
Expand Down Expand Up @@ -408,7 +407,7 @@ def marshall_file(
else:
raise RuntimeError("Invalid binary data format: %s" % type(data))

if streamlit._is_running_with_streamlit:
if runtime.exists():
file_url = runtime.get_instance().media_file_mgr.add(
data_as_bytes,
mimetype,
Expand Down
3 changes: 2 additions & 1 deletion lib/streamlit/elements/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from typing import NamedTuple, Optional, cast

import streamlit
from streamlit import runtime
from streamlit.errors import StreamlitAPIException
from streamlit.proto import Block_pb2
from streamlit.runtime.metrics_util import gather_metrics
Expand All @@ -38,7 +39,7 @@ def _current_form(
To find the current form, we walk up the dg_stack until we find
a DeltaGenerator that has FormData.
"""
if not streamlit._is_running_with_streamlit:
if not runtime.exists():
return None

if this_dg._form_data is not None:
Expand Down
Loading

0 comments on commit adde74a

Please sign in to comment.