Skip to content

Commit

Permalink
Move check_* utils to own file
Browse files Browse the repository at this point in the history
  • Loading branch information
raethlein committed May 26, 2024
1 parent 3904769 commit b5aad90
Show file tree
Hide file tree
Showing 20 changed files with 329 additions and 255 deletions.
2 changes: 1 addition & 1 deletion lib/streamlit/elements/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def form(
"""
# Import this here to avoid circular imports.
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_session_state_rules,
)
Expand Down
2 changes: 1 addition & 1 deletion lib/streamlit/elements/plotly_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ def plotly_chart(
# Run some checks that are only relevant when selections are activated

# Import here to avoid circular imports
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
Expand Down
102 changes: 102 additions & 0 deletions lib/streamlit/elements/policies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

from typing import TYPE_CHECKING, Any

import streamlit

Check notice

Code scanning / CodeQL

Module is imported with 'import' and 'import from' Note

Module 'streamlit' is imported with both 'import' and 'import from'.
from streamlit import config, runtime
from streamlit.elements.form import is_in_form
from streamlit.errors import StreamlitAPIException, StreamlitAPIWarning
from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx

Check notice

Code scanning / CodeQL

Unused import Note

Import of 'get_script_run_ctx' is not used.
from streamlit.runtime.state import WidgetCallback, get_session_state

if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator


def check_callback_rules(dg: DeltaGenerator, on_change: WidgetCallback | None) -> None:
if runtime.exists() and is_in_form(dg) and on_change is not None:
raise StreamlitAPIException(
"With forms, callbacks can only be defined on the `st.form_submit_button`."
" Defining callbacks on other widgets inside a form is not allowed."
)


_shown_default_value_warning: bool = False


def check_session_state_rules(
default_value: Any, key: str | None, writes_allowed: bool = True
) -> None:
global _shown_default_value_warning

if key is None or not runtime.exists():
return

session_state = get_session_state()
if not session_state.is_new_state_value(key):
return

if not writes_allowed:
raise StreamlitAPIException(
f'Values for the widget with key "{key}" cannot be set using `st.session_state`.'
)

if (
default_value is not None
and not _shown_default_value_warning
and not config.get_option("global.disableWidgetStateDuplicationWarning")
):
streamlit.warning(
f'The widget with key "{key}" was created with a default value but'
" also had its value set via the Session State API."
)
_shown_default_value_warning = True


class CachedWidgetWarning(StreamlitAPIWarning):
def __init__(self):
super().__init__(
"""
Your script uses a widget command in a cached function
(function decorated with `@st.cache_data` or `@st.cache_resource`).
This code will only be called when we detect a cache "miss",
which can lead to unexpected results.
How to fix this:
* Move all widget commands outside the cached function.
* Or, if you know what you're doing, use `experimental_allow_widgets=True`
in the cache decorator to enable widget replay and suppress this warning.
"""
)


def check_cache_replay_rules() -> None:
"""Check if a widget is allowed to be used in the current context.
More specifically, this checks if the current context is inside a
cached function that disallows widget usage. If so, it raises a warning.
If there are other similar checks in the future, we could extend this
function to check for those as well. And rename it to check_widget_usage_rules.
"""
if runtime.exists():
from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx

ctx = get_script_run_ctx()
if ctx and ctx.disallow_cached_widget_usage:
# We use an exception here to show a proper stack trace
# that indicates to the user where the issue is.
streamlit.exception(CachedWidgetWarning())
98 changes: 6 additions & 92 deletions lib/streamlit/elements/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,95 +15,13 @@
from __future__ import annotations

from enum import Enum, EnumMeta
from typing import TYPE_CHECKING, Any, Iterable, Sequence, overload
from typing import Any, Iterable, Sequence, overload

import streamlit
from streamlit import config, runtime, type_util
from streamlit.elements.form import is_in_form
from streamlit.errors import StreamlitAPIException, StreamlitAPIWarning
from streamlit import type_util
from streamlit.proto.LabelVisibilityMessage_pb2 import LabelVisibilityMessage
from streamlit.runtime.state import WidgetCallback, get_session_state
from streamlit.runtime.state.common import RegisterWidgetResult
from streamlit.type_util import T

if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator


def check_callback_rules(dg: DeltaGenerator, on_change: WidgetCallback | None) -> None:
if runtime.exists() and is_in_form(dg) and on_change is not None:
raise StreamlitAPIException(
"With forms, callbacks can only be defined on the `st.form_submit_button`."
" Defining callbacks on other widgets inside a form is not allowed."
)


_shown_default_value_warning: bool = False


def check_session_state_rules(
default_value: Any, key: str | None, writes_allowed: bool = True
) -> None:
global _shown_default_value_warning

if key is None or not runtime.exists():
return

session_state = get_session_state()
if not session_state.is_new_state_value(key):
return

if not writes_allowed:
raise StreamlitAPIException(
f'Values for the widget with key "{key}" cannot be set using `st.session_state`.'
)

if (
default_value is not None
and not _shown_default_value_warning
and not config.get_option("global.disableWidgetStateDuplicationWarning")
):
streamlit.warning(
f'The widget with key "{key}" was created with a default value but'
" also had its value set via the Session State API."
)
_shown_default_value_warning = True


class CachedWidgetWarning(StreamlitAPIWarning):
def __init__(self):
super().__init__(
"""
Your script uses a widget command in a cached function
(function decorated with `@st.cache_data` or `@st.cache_resource`).
This code will only be called when we detect a cache "miss",
which can lead to unexpected results.
How to fix this:
* Move all widget commands outside the cached function.
* Or, if you know what you're doing, use `experimental_allow_widgets=True`
in the cache decorator to enable widget replay and suppress this warning.
"""
)


def check_cache_replay_rules() -> None:
"""Check if a widget is allowed to be used in the current context.
More specifically, this checks if the current context is inside a
cached function that disallows widget usage. If so, it raises a warning.
If there are other similar checks in the future, we could extend this
function to check for those as well. And rename it to check_widget_usage_rules.
"""
if runtime.exists():
from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx

ctx = get_script_run_ctx()
if ctx and ctx.disallow_cached_widget_usage:
# We use an exception here to show a proper stack trace
# that indicates to the user where the issue is.
streamlit.exception(CachedWidgetWarning())


def get_label_visibility_proto_value(
label_visibility_string: type_util.LabelVisibility,
Expand All @@ -125,17 +43,15 @@ def maybe_coerce_enum(
register_widget_result: RegisterWidgetResult[Enum],
options: type[Enum],
opt_sequence: Sequence[Any],
) -> RegisterWidgetResult[Enum]:
...
) -> RegisterWidgetResult[Enum]: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.


@overload
def maybe_coerce_enum(
register_widget_result: RegisterWidgetResult[T],
options: type_util.OptionSequence[T],
opt_sequence: Sequence[T],
) -> RegisterWidgetResult[T]:
...
) -> RegisterWidgetResult[T]: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.


def maybe_coerce_enum(register_widget_result, options, opt_sequence):
Expand Down Expand Up @@ -168,17 +84,15 @@ def maybe_coerce_enum_sequence(
register_widget_result: RegisterWidgetResult[list[T]],
options: type_util.OptionSequence[T],
opt_sequence: Sequence[T],
) -> RegisterWidgetResult[list[T]]:
...
) -> RegisterWidgetResult[list[T]]: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.


@overload
def maybe_coerce_enum_sequence(
register_widget_result: RegisterWidgetResult[tuple[T, T]],
options: type_util.OptionSequence[T],
opt_sequence: Sequence[T],
) -> RegisterWidgetResult[tuple[T, T]]:
...
) -> RegisterWidgetResult[tuple[T, T]]: ...

Check notice

Code scanning / CodeQL

Statement has no effect Note

This statement has no effect.


def maybe_coerce_enum_sequence(register_widget_result, options, opt_sequence):
Expand Down
2 changes: 1 addition & 1 deletion lib/streamlit/elements/vega_charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -1652,7 +1652,7 @@ def _vega_lite_chart(
# Run some checks that are only relevant when selections are activated

# Import here to avoid circular imports
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
Expand Down
4 changes: 2 additions & 2 deletions lib/streamlit/elements/widgets/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,7 @@ def _download_button(
key = to_key(key)

# Importing these functions here to avoid circular imports
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
Expand Down Expand Up @@ -739,7 +739,7 @@ def _button(
key = to_key(key)

# Importing these functions here to avoid circular imports
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
Expand Down
4 changes: 2 additions & 2 deletions lib/streamlit/elements/widgets/camera_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
from typing_extensions import TypeAlias

from streamlit.elements.form import current_form_id
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
get_label_visibility_proto_value,
)

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
streamlit.elements.policies
begins an import cycle.
from streamlit.elements.utils import get_label_visibility_proto_value
from streamlit.elements.widgets.file_uploader import _get_upload_files
from streamlit.proto.CameraInput_pb2 import CameraInput as CameraInputProto
from streamlit.proto.Common_pb2 import FileUploaderState as FileUploaderStateProto
Expand Down
2 changes: 1 addition & 1 deletion lib/streamlit/elements/widgets/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def chat_input(
default = ""
key = to_key(key)

from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
Expand Down
4 changes: 2 additions & 2 deletions lib/streamlit/elements/widgets/checkbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
from typing import TYPE_CHECKING, cast

from streamlit.elements.form import current_form_id
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
get_label_visibility_proto_value,
)

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
streamlit.elements.policies
begins an import cycle.
from streamlit.elements.utils import get_label_visibility_proto_value
from streamlit.proto.Checkbox_pb2 import Checkbox as CheckboxProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx
Expand Down
4 changes: 2 additions & 2 deletions lib/streamlit/elements/widgets/color_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@

import streamlit
from streamlit.elements.form import current_form_id
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
get_label_visibility_proto_value,
)

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
streamlit.elements.policies
begins an import cycle.
from streamlit.elements.utils import get_label_visibility_proto_value
from streamlit.errors import StreamlitAPIException
from streamlit.proto.ColorPicker_pb2 import ColorPicker as ColorPickerProto
from streamlit.runtime.metrics_util import gather_metrics
Expand Down
4 changes: 2 additions & 2 deletions lib/streamlit/elements/widgets/file_uploader.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@

from streamlit import config
from streamlit.elements.form import current_form_id
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
get_label_visibility_proto_value,
)

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
streamlit.elements.policies
begins an import cycle.
from streamlit.elements.utils import get_label_visibility_proto_value
from streamlit.proto.Common_pb2 import FileUploaderState as FileUploaderStateProto
from streamlit.proto.Common_pb2 import UploadedFileInfo as UploadedFileInfoProto
from streamlit.proto.FileUploader_pb2 import FileUploader as FileUploaderProto
Expand Down
4 changes: 3 additions & 1 deletion lib/streamlit/elements/widgets/multiselect.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
from typing import TYPE_CHECKING, Any, Callable, Generic, Sequence, cast, overload

from streamlit.elements.form import current_form_id
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
)

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
streamlit.elements.policies
begins an import cycle.
from streamlit.elements.utils import (
get_label_visibility_proto_value,
maybe_coerce_enum_sequence,
)
Expand Down
4 changes: 2 additions & 2 deletions lib/streamlit/elements/widgets/number_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@
from typing_extensions import TypeAlias

from streamlit.elements.form import current_form_id
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
get_label_visibility_proto_value,
)

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
streamlit.elements.policies
begins an import cycle.
from streamlit.elements.utils import get_label_visibility_proto_value
from streamlit.errors import StreamlitAPIException
from streamlit.js_number import JSNumber, JSNumberBoundsException
from streamlit.proto.NumberInput_pb2 import NumberInput as NumberInputProto
Expand Down
5 changes: 2 additions & 3 deletions lib/streamlit/elements/widgets/radio.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@
from typing import TYPE_CHECKING, Any, Callable, Generic, Sequence, cast

from streamlit.elements.form import current_form_id
from streamlit.elements.utils import (
from streamlit.elements.policies import (
check_cache_replay_rules,
check_callback_rules,
check_session_state_rules,
get_label_visibility_proto_value,
maybe_coerce_enum,
)

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
streamlit.elements.policies
begins an import cycle.
from streamlit.elements.utils import get_label_visibility_proto_value, maybe_coerce_enum
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Radio_pb2 import Radio as RadioProto
from streamlit.runtime.metrics_util import gather_metrics
Expand Down
Loading

0 comments on commit b5aad90

Please sign in to comment.