streamlit-nightly 1.35.1.dev20240610__py2.py3-none-any.whl → 1.35.1.dev20240611__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. streamlit/__init__.py +5 -1
  2. streamlit/case_converters.py +2 -2
  3. streamlit/cli_util.py +2 -2
  4. streamlit/color_util.py +2 -2
  5. streamlit/commands/experimental_query_params.py +6 -8
  6. streamlit/commands/logo.py +4 -9
  7. streamlit/commands/navigation.py +6 -4
  8. streamlit/components/lib/local_component_registry.py +4 -2
  9. streamlit/components/types/base_component_registry.py +3 -2
  10. streamlit/components/v1/component_arrow.py +2 -1
  11. streamlit/components/v1/component_registry.py +6 -2
  12. streamlit/components/v1/components.py +4 -2
  13. streamlit/components/v1/custom_component.py +6 -6
  14. streamlit/config.py +15 -12
  15. streamlit/connections/snowflake_connection.py +2 -1
  16. streamlit/connections/snowpark_connection.py +2 -4
  17. streamlit/connections/sql_connection.py +2 -1
  18. streamlit/delta_generator.py +3 -4
  19. streamlit/elements/arrow.py +3 -6
  20. streamlit/elements/code.py +1 -1
  21. streamlit/elements/dialog_decorator.py +10 -8
  22. streamlit/elements/doc_string.py +1 -1
  23. streamlit/elements/exception.py +1 -1
  24. streamlit/elements/form.py +1 -1
  25. streamlit/elements/heading.py +1 -1
  26. streamlit/elements/html.py +1 -1
  27. streamlit/elements/image.py +5 -3
  28. streamlit/elements/layouts.py +7 -7
  29. streamlit/elements/lib/built_in_chart_utils.py +24 -12
  30. streamlit/elements/lib/column_config_utils.py +2 -1
  31. streamlit/elements/lib/dialog.py +8 -5
  32. streamlit/elements/lib/dicttools.py +3 -3
  33. streamlit/elements/lib/mutable_status_container.py +8 -5
  34. streamlit/elements/lib/pandas_styler_utils.py +2 -1
  35. streamlit/elements/lib/subtitle_utils.py +0 -1
  36. streamlit/elements/lib/utils.py +8 -10
  37. streamlit/elements/plotly_chart.py +5 -10
  38. streamlit/elements/pyplot.py +0 -1
  39. streamlit/elements/toast.py +2 -2
  40. streamlit/elements/vega_charts.py +46 -10
  41. streamlit/elements/widgets/color_picker.py +6 -4
  42. streamlit/elements/widgets/file_uploader.py +4 -8
  43. streamlit/elements/widgets/multiselect.py +2 -4
  44. streamlit/elements/widgets/number_input.py +4 -8
  45. streamlit/elements/widgets/select_slider.py +1 -1
  46. streamlit/elements/widgets/slider.py +2 -5
  47. streamlit/elements/widgets/time_widgets.py +5 -5
  48. streamlit/errors.py +1 -6
  49. streamlit/git_util.py +2 -2
  50. streamlit/hello/Animation_Demo.py +0 -1
  51. streamlit/logger.py +1 -1
  52. streamlit/navigation/page.py +6 -1
  53. streamlit/net_util.py +2 -5
  54. streamlit/proto/AutoRerun_pb2.py +3 -2
  55. streamlit/runtime/app_session.py +7 -7
  56. streamlit/runtime/caching/__init__.py +9 -13
  57. streamlit/runtime/caching/cache_data_api.py +18 -7
  58. streamlit/runtime/caching/cache_errors.py +8 -6
  59. streamlit/runtime/caching/cache_resource_api.py +10 -9
  60. streamlit/runtime/caching/cache_utils.py +10 -7
  61. streamlit/runtime/caching/cached_message_replay.py +10 -9
  62. streamlit/runtime/caching/hashing.py +3 -3
  63. streamlit/runtime/caching/storage/cache_storage_protocol.py +1 -1
  64. streamlit/runtime/connection_factory.py +4 -2
  65. streamlit/runtime/credentials.py +11 -20
  66. streamlit/runtime/forward_msg_cache.py +10 -11
  67. streamlit/runtime/forward_msg_queue.py +6 -4
  68. streamlit/runtime/fragment.py +7 -9
  69. streamlit/runtime/media_file_manager.py +4 -4
  70. streamlit/runtime/memory_media_file_storage.py +7 -8
  71. streamlit/runtime/metrics_util.py +2 -4
  72. streamlit/runtime/pages_manager.py +41 -41
  73. streamlit/runtime/runtime.py +4 -4
  74. streamlit/runtime/runtime_util.py +7 -12
  75. streamlit/runtime/scriptrunner/magic.py +1 -1
  76. streamlit/runtime/scriptrunner/script_requests.py +4 -2
  77. streamlit/runtime/scriptrunner/script_run_context.py +15 -15
  78. streamlit/runtime/scriptrunner/script_runner.py +8 -8
  79. streamlit/runtime/secrets.py +3 -5
  80. streamlit/runtime/session_manager.py +8 -7
  81. streamlit/runtime/state/common.py +1 -1
  82. streamlit/runtime/state/query_params_proxy.py +5 -10
  83. streamlit/runtime/state/safe_session_state.py +8 -7
  84. streamlit/runtime/state/widgets.py +27 -27
  85. streamlit/runtime/stats.py +1 -1
  86. streamlit/runtime/uploaded_file_manager.py +4 -2
  87. streamlit/runtime/websocket_session_manager.py +6 -4
  88. streamlit/string_util.py +1 -1
  89. streamlit/testing/v1/app_test.py +4 -2
  90. streamlit/testing/v1/element_tree.py +33 -37
  91. streamlit/testing/v1/local_script_runner.py +7 -7
  92. streamlit/time_util.py +2 -4
  93. streamlit/type_util.py +16 -29
  94. streamlit/user_info.py +4 -2
  95. streamlit/util.py +1 -1
  96. streamlit/watcher/event_based_path_watcher.py +6 -3
  97. streamlit/watcher/local_sources_watcher.py +11 -7
  98. streamlit/web/bootstrap.py +1 -1
  99. streamlit/web/cache_storage_manager_config.py +5 -1
  100. streamlit/web/cli.py +9 -4
  101. streamlit/web/server/browser_websocket_handler.py +7 -8
  102. streamlit/web/server/component_request_handler.py +4 -2
  103. streamlit/web/server/routes.py +3 -3
  104. streamlit/web/server/server.py +12 -12
  105. streamlit/web/server/server_util.py +5 -6
  106. streamlit/web/server/stats_request_handler.py +1 -1
  107. streamlit/web/server/upload_file_request_handler.py +5 -3
  108. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240611.dist-info}/METADATA +1 -1
  109. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240611.dist-info}/RECORD +113 -113
  110. {streamlit_nightly-1.35.1.dev20240610.data → streamlit_nightly-1.35.1.dev20240611.data}/scripts/streamlit.cmd +0 -0
  111. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240611.dist-info}/WHEEL +0 -0
  112. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240611.dist-info}/entry_points.txt +0 -0
  113. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240611.dist-info}/top_level.txt +0 -0
@@ -162,8 +162,7 @@ class FileUploaderMixin:
162
162
  *,
163
163
  disabled: bool = False,
164
164
  label_visibility: LabelVisibility = "visible",
165
- ) -> list[UploadedFile] | None:
166
- ...
165
+ ) -> list[UploadedFile] | None: ...
167
166
 
168
167
  # 1. type is given as not a keyword-only argument
169
168
  # 2. accept_multiple_files = False or omitted
@@ -181,8 +180,7 @@ class FileUploaderMixin:
181
180
  *,
182
181
  disabled: bool = False,
183
182
  label_visibility: LabelVisibility = "visible",
184
- ) -> UploadedFile | None:
185
- ...
183
+ ) -> UploadedFile | None: ...
186
184
 
187
185
  # The following 2 overloads represent the cases where
188
186
  # the `type` argument is a keyword-only argument.
@@ -205,8 +203,7 @@ class FileUploaderMixin:
205
203
  kwargs: WidgetKwargs | None = None,
206
204
  disabled: bool = False,
207
205
  label_visibility: LabelVisibility = "visible",
208
- ) -> list[UploadedFile] | None:
209
- ...
206
+ ) -> list[UploadedFile] | None: ...
210
207
 
211
208
  # 1. type is skipped or a keyword argument
212
209
  # 2. accept_multiple_files = False or omitted
@@ -224,8 +221,7 @@ class FileUploaderMixin:
224
221
  kwargs: WidgetKwargs | None = None,
225
222
  disabled: bool = False,
226
223
  label_visibility: LabelVisibility = "visible",
227
- ) -> UploadedFile | None:
228
- ...
224
+ ) -> UploadedFile | None: ...
229
225
 
230
226
  @gather_metrics("file_uploader")
231
227
  def file_uploader(
@@ -60,15 +60,13 @@ if TYPE_CHECKING:
60
60
  @overload
61
61
  def _check_and_convert_to_indices( # type: ignore[misc]
62
62
  opt: Sequence[Any], default_values: None
63
- ) -> list[int] | None:
64
- ...
63
+ ) -> list[int] | None: ...
65
64
 
66
65
 
67
66
  @overload
68
67
  def _check_and_convert_to_indices(
69
68
  opt: Sequence[Any], default_values: Sequence[Any] | Any
70
- ) -> list[int]:
71
- ...
69
+ ) -> list[int]: ...
72
70
 
73
71
 
74
72
  def _check_and_convert_to_indices(
@@ -401,17 +401,13 @@ class NumberInputMixin:
401
401
  try:
402
402
  if all_ints:
403
403
  if min_value is not None:
404
- JSNumber.validate_int_bounds(
405
- min_value, "`min_value`" # type: ignore
406
- )
404
+ JSNumber.validate_int_bounds(int(min_value), "`min_value`")
407
405
  if max_value is not None:
408
- JSNumber.validate_int_bounds(
409
- max_value, "`max_value`" # type: ignore
410
- )
406
+ JSNumber.validate_int_bounds(int(max_value), "`max_value`")
411
407
  if step is not None:
412
- JSNumber.validate_int_bounds(step, "`step`") # type: ignore
408
+ JSNumber.validate_int_bounds(int(step), "`step`")
413
409
  if value is not None:
414
- JSNumber.validate_int_bounds(value, "`value`") # type: ignore
410
+ JSNumber.validate_int_bounds(int(value), "`value`")
415
411
  else:
416
412
  if min_value is not None:
417
413
  JSNumber.validate_float_bounds(min_value, "`min_value`")
@@ -87,7 +87,7 @@ class SelectSliderSerde(Generic[T]):
87
87
  # The widget always returns floats, so convert to ints before indexing
88
88
  return_value: tuple[T, T] = cast(
89
89
  Tuple[T, T],
90
- tuple(map(lambda x: self.options[int(x)], ui_value)),
90
+ tuple(self.options[int(x)] for x in ui_value),
91
91
  )
92
92
 
93
93
  # If the original value was a list/tuple, so will be the output (and vice versa)
@@ -519,12 +519,9 @@ class SliderMixin:
519
519
 
520
520
  # Ensure that all arguments are of the same type.
521
521
  slider_args = [min_value, max_value, step]
522
- int_args = all(map(lambda a: isinstance(a, Integral), slider_args))
522
+ int_args = all(isinstance(a, Integral) for a in slider_args)
523
523
  float_args = all(
524
- map(
525
- lambda a: isinstance(a, Real) and not isinstance(a, Integral),
526
- slider_args,
527
- )
524
+ isinstance(a, Real) and not isinstance(a, Integral) for a in slider_args
528
525
  )
529
526
  # When min and max_value are the same timelike, step should be a timedelta
530
527
  timelike_args = (
@@ -72,7 +72,7 @@ ALLOWED_DATE_FORMATS: Final = re.compile(
72
72
 
73
73
 
74
74
  def _parse_date_value(
75
- value: DateValue | Literal["today"] | Literal["default_value_today"],
75
+ value: Literal["today", "default_value_today"] | DateValue,
76
76
  ) -> tuple[list[date] | None, bool]:
77
77
  parsed_dates: list[date]
78
78
  range_value: bool = False
@@ -87,7 +87,7 @@ def _parse_date_value(
87
87
  elif isinstance(value, date):
88
88
  parsed_dates = [value]
89
89
  elif isinstance(value, (list, tuple)):
90
- if not len(value) in (0, 1, 2):
90
+ if len(value) not in {0, 1, 2}:
91
91
  raise StreamlitAPIException(
92
92
  "DateInput value should either be an date/datetime or a list/tuple of "
93
93
  "0 - 2 date/datetime values"
@@ -155,7 +155,7 @@ class _DateInputValues:
155
155
  @classmethod
156
156
  def from_raw_values(
157
157
  cls,
158
- value: DateValue | Literal["today"] | Literal["default_value_today"],
158
+ value: Literal["today", "default_value_today"] | DateValue,
159
159
  min_value: SingleDateValue,
160
160
  max_value: SingleDateValue,
161
161
  ) -> _DateInputValues:
@@ -677,7 +677,7 @@ class TimeWidgetsMixin:
677
677
  self,
678
678
  label: str,
679
679
  value: (
680
- DateValue | Literal["today"] | Literal["default_value_today"]
680
+ Literal["today", "default_value_today"] | DateValue
681
681
  ) = "default_value_today",
682
682
  min_value: SingleDateValue = None,
683
683
  max_value: SingleDateValue = None,
@@ -703,7 +703,7 @@ class TimeWidgetsMixin:
703
703
  maybe_raise_label_warnings(label, label_visibility)
704
704
 
705
705
  def parse_date_deterministic(
706
- v: SingleDateValue | Literal["today"] | Literal["default_value_today"],
706
+ v: SingleDateValue | Literal["today", "default_value_today"],
707
707
  ) -> str | None:
708
708
  if isinstance(v, datetime):
709
709
  return date.strftime(v.date(), "%Y/%m/%d")
streamlit/errors.py CHANGED
@@ -130,12 +130,7 @@ or in your `.streamlit/config.toml`
130
130
  [deprecation]
131
131
  {2} = false
132
132
  ```
133
- """.format(
134
- msg, config_option, config_option.split(".")[1]
135
- )
136
- # TODO: create a deprecation docs page to add to deprecation msg #1669
137
- # For more details, please see: https://docs.streamlit.io/path/to/deprecation/docs.html
138
-
133
+ """.format(msg, config_option, config_option.split(".")[1])
139
134
  super().__init__(message, *args)
140
135
 
141
136
  def __repr__(self) -> str:
streamlit/git_util.py CHANGED
@@ -106,11 +106,11 @@ class GitRepo:
106
106
 
107
107
  try:
108
108
  remote, branch_name = self.get_tracking_branch_remote()
109
- remote_branch = "/".join([remote.name, branch_name])
109
+ remote_branch = f"{remote.name}/{branch_name}"
110
110
 
111
111
  return list(self.repo.iter_commits(f"{remote_branch}..{branch_name}"))
112
112
  except Exception:
113
- return list()
113
+ return []
114
114
 
115
115
  def get_tracking_branch_remote(self):
116
116
  if not self.is_valid():
@@ -21,7 +21,6 @@ from streamlit.hello.utils import show_code
21
21
 
22
22
 
23
23
  def animation_demo() -> None:
24
-
25
24
  # Interactive Streamlit elements, like these sliders, return their value.
26
25
  # This gives you an extremely simple interaction model.
27
26
  iterations = st.sidebar.slider("Level of detail", 2, 20, 10, 1)
streamlit/logger.py CHANGED
@@ -20,7 +20,7 @@ import logging
20
20
  import sys
21
21
  from typing import Final
22
22
 
23
- DEFAULT_LOG_MESSAGE: Final = "%(asctime)s %(levelname) -7s " "%(name)s: %(message)s"
23
+ DEFAULT_LOG_MESSAGE: Final = "%(asctime)s %(levelname) -7s %(name)s: %(message)s"
24
24
 
25
25
  # Loggers for each name are saved here.
26
26
  _loggers: dict[str, logging.Logger] = {}
@@ -35,7 +35,7 @@ def Page(
35
35
  url_path: str | None = None,
36
36
  default: bool = False,
37
37
  ):
38
- """Configure a page in `st.navigation` in a multipage app.
38
+ """Configure a page in `st.navigation` in a multipage app.
39
39
 
40
40
  The Page object is passed to `st.navigation` and returned when the user
41
41
  navigates to that page. Call `Page.run()` on the returned Page in your
@@ -119,6 +119,11 @@ class StreamlitPage:
119
119
  if isinstance(page, Path):
120
120
  page = (main_path / page).resolve()
121
121
 
122
+ if not page.is_file():
123
+ raise StreamlitAPIException(
124
+ f"Unable to create Page. The file `{page.name}` could not be found."
125
+ )
126
+
122
127
  inferred_name = ""
123
128
  inferred_icon = ""
124
129
  if isinstance(page, Path):
streamlit/net_util.py CHANGED
@@ -52,11 +52,8 @@ def get_external_ip() -> str | None:
52
52
  _external_ip = response
53
53
  else:
54
54
  _LOGGER.warning(
55
- # fmt: off
56
- "Did not auto detect external IP.\n"
57
- "Please go to %s for debugging hints.",
58
- # fmt: on
59
- util.HELP_DOC
55
+ "Did not auto detect external IP.\nPlease go to %s for debugging hints.",
56
+ util.HELP_DOC,
60
57
  )
61
58
  _external_ip = None
62
59
 
@@ -14,13 +14,14 @@ _sym_db = _symbol_database.Default()
14
14
 
15
15
 
16
16
 
17
- DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1fstreamlit/proto/AutoRerun.proto\"2\n\tAutoRerun\x12\x10\n\x08interval\x18\x01 \x01(\x02\x12\x13\n\x0b\x66ragment_id\x18\x02 \x01(\tb\x06proto3')
17
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1fstreamlit/proto/AutoRerun.proto\"2\n\tAutoRerun\x12\x10\n\x08interval\x18\x01 \x01(\x02\x12\x13\n\x0b\x66ragment_id\x18\x02 \x01(\tB.\n\x1c\x63om.snowflake.apps.streamlitB\x0e\x41utoRerunProtob\x06proto3')
18
18
 
19
19
  _globals = globals()
20
20
  _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
21
21
  _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'streamlit.proto.AutoRerun_pb2', _globals)
22
22
  if not _descriptor._USE_C_DESCRIPTORS:
23
- DESCRIPTOR._loaded_options = None
23
+ _globals['DESCRIPTOR']._loaded_options = None
24
+ _globals['DESCRIPTOR']._serialized_options = b'\n\034com.snowflake.apps.streamlitB\016AutoRerunProto'
24
25
  _globals['_AUTORERUN']._serialized_start=35
25
26
  _globals['_AUTORERUN']._serialized_end=85
26
27
  # @@protoc_insertion_point(module_scope)
@@ -24,7 +24,6 @@ import streamlit.elements.exception as exception_utils
24
24
  from streamlit import config, runtime
25
25
  from streamlit.case_converters import to_snake_case
26
26
  from streamlit.logger import get_logger
27
- from streamlit.proto.BackMsg_pb2 import BackMsg
28
27
  from streamlit.proto.ClientState_pb2 import ClientState
29
28
  from streamlit.proto.Common_pb2 import FileURLs, FileURLsRequest
30
29
  from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
@@ -35,23 +34,24 @@ from streamlit.proto.NewSession_pb2 import (
35
34
  NewSession,
36
35
  UserInfo,
37
36
  )
38
- from streamlit.proto.PagesChanged_pb2 import PagesChanged
39
37
  from streamlit.runtime import caching
40
38
  from streamlit.runtime.forward_msg_queue import ForwardMsgQueue
41
39
  from streamlit.runtime.fragment import FragmentStorage, MemoryFragmentStorage
42
40
  from streamlit.runtime.metrics_util import Installation
43
41
  from streamlit.runtime.pages_manager import PagesManager
44
- from streamlit.runtime.script_data import ScriptData
45
42
  from streamlit.runtime.scriptrunner import RerunData, ScriptRunner, ScriptRunnerEvent
46
- from streamlit.runtime.scriptrunner.script_cache import ScriptCache
47
43
  from streamlit.runtime.secrets import secrets_singleton
48
- from streamlit.runtime.uploaded_file_manager import UploadedFileManager
49
- from streamlit.source_util import PageHash, PageInfo
50
44
  from streamlit.version import STREAMLIT_VERSION_STRING
51
45
  from streamlit.watcher import LocalSourcesWatcher
52
46
 
53
47
  if TYPE_CHECKING:
48
+ from streamlit.proto.BackMsg_pb2 import BackMsg
49
+ from streamlit.proto.PagesChanged_pb2 import PagesChanged
50
+ from streamlit.runtime.script_data import ScriptData
51
+ from streamlit.runtime.scriptrunner.script_cache import ScriptCache
54
52
  from streamlit.runtime.state import SessionState
53
+ from streamlit.runtime.uploaded_file_manager import UploadedFileManager
54
+ from streamlit.source_util import PageHash, PageInfo
55
55
 
56
56
  _LOGGER: Final = get_logger(__name__)
57
57
 
@@ -881,7 +881,7 @@ def _populate_config_msg(msg: Config) -> None:
881
881
  msg.hide_top_bar = config.get_option("ui.hideTopBar")
882
882
  # ui.hideSidebarNav is deprecated, will be removed in the future
883
883
  msg.hide_sidebar_nav = config.get_option("ui.hideSidebarNav")
884
- if config.get_option("client.showSidebarNavigation") == False:
884
+ if config.get_option("client.showSidebarNavigation") is False:
885
885
  msg.hide_sidebar_nav = True
886
886
  msg.toolbar_mode = _get_toolbar_mode()
887
887
 
@@ -14,24 +14,26 @@
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
- from typing import Any
17
+ from typing import TYPE_CHECKING, Any
18
18
 
19
- from google.protobuf.message import Message
20
-
21
- from streamlit.proto.Block_pb2 import Block
22
19
  from streamlit.runtime.caching.cache_data_api import (
23
20
  CACHE_DATA_MESSAGE_REPLAY_CTX,
24
21
  CacheDataAPI,
25
- _data_caches,
22
+ get_data_cache_stats_provider,
26
23
  )
27
24
  from streamlit.runtime.caching.cache_errors import CACHE_DOCS_URL
28
25
  from streamlit.runtime.caching.cache_resource_api import (
29
26
  CACHE_RESOURCE_MESSAGE_REPLAY_CTX,
30
27
  CacheResourceAPI,
31
- _resource_caches,
28
+ get_resource_cache_stats_provider,
32
29
  )
33
30
  from streamlit.runtime.caching.legacy_cache_api import cache as _cache
34
- from streamlit.runtime.state.common import WidgetMetadata
31
+
32
+ if TYPE_CHECKING:
33
+ from google.protobuf.message import Message
34
+
35
+ from streamlit.proto.Block_pb2 import Block
36
+ from streamlit.runtime.state.common import WidgetMetadata
35
37
 
36
38
 
37
39
  def save_element_message(
@@ -84,12 +86,6 @@ def save_media_data(image_data: bytes | str, mimetype: str, image_id: str) -> No
84
86
  CACHE_RESOURCE_MESSAGE_REPLAY_CTX.save_image_data(image_data, mimetype, image_id)
85
87
 
86
88
 
87
- # Explicitly export public symbols
88
- from streamlit.runtime.caching.cache_data_api import get_data_cache_stats_provider
89
- from streamlit.runtime.caching.cache_resource_api import (
90
- get_resource_cache_stats_provider,
91
- )
92
-
93
89
  # Create and export public API singletons.
94
90
  cache_data = CacheDataAPI(decorator_metric_name="cache_data")
95
91
  cache_resource = CacheResourceAPI(decorator_metric_name="cache_resource")
@@ -19,8 +19,17 @@ from __future__ import annotations
19
19
  import pickle
20
20
  import threading
21
21
  import types
22
- from datetime import timedelta
23
- from typing import Any, Callable, Final, Literal, TypeVar, Union, cast, overload
22
+ from typing import (
23
+ TYPE_CHECKING,
24
+ Any,
25
+ Callable,
26
+ Final,
27
+ Literal,
28
+ TypeVar,
29
+ Union,
30
+ cast,
31
+ overload,
32
+ )
24
33
 
25
34
  from typing_extensions import TypeAlias
26
35
 
@@ -44,7 +53,6 @@ from streamlit.runtime.caching.cached_message_replay import (
44
53
  MultiCacheResults,
45
54
  show_widget_replay_deprecation,
46
55
  )
47
- from streamlit.runtime.caching.hashing import HashFuncsDict
48
56
  from streamlit.runtime.caching.storage import (
49
57
  CacheStorage,
50
58
  CacheStorageContext,
@@ -63,6 +71,11 @@ from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx
63
71
  from streamlit.runtime.stats import CacheStat, CacheStatsProvider, group_stats
64
72
  from streamlit.time_util import time_to_seconds
65
73
 
74
+ if TYPE_CHECKING:
75
+ from datetime import timedelta
76
+
77
+ from streamlit.runtime.caching.hashing import HashFuncsDict
78
+
66
79
  _LOGGER: Final = get_logger(__name__)
67
80
 
68
81
  CACHE_DATA_MESSAGE_REPLAY_CTX = CachedMessageReplayContext(CacheType.DATA)
@@ -344,8 +357,7 @@ class CacheDataAPI:
344
357
 
345
358
  # Bare decorator usage
346
359
  @overload
347
- def __call__(self, func: F) -> F:
348
- ...
360
+ def __call__(self, func: F) -> F: ...
349
361
 
350
362
  # Decorator with arguments
351
363
  @overload
@@ -358,8 +370,7 @@ class CacheDataAPI:
358
370
  persist: CachePersistType | bool = None,
359
371
  experimental_allow_widgets: bool = False,
360
372
  hash_funcs: HashFuncsDict | None = None,
361
- ) -> Callable[[F], F]:
362
- ...
373
+ ) -> Callable[[F], F]: ...
363
374
 
364
375
  def __call__(
365
376
  self,
@@ -14,13 +14,15 @@
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
- import types
18
- from typing import Any
17
+ from typing import TYPE_CHECKING, Any
19
18
 
20
19
  from streamlit import type_util
21
20
  from streamlit.errors import MarkdownFormattedException, StreamlitAPIException
22
21
  from streamlit.runtime.caching.cache_type import CacheType, get_decorator_api_name
23
22
 
23
+ if TYPE_CHECKING:
24
+ from types import FunctionType
25
+
24
26
  CACHE_DOCS_URL = "https://docs.streamlit.io/library/advanced-features/caching"
25
27
 
26
28
 
@@ -47,7 +49,7 @@ class UnhashableParamError(StreamlitAPIException):
47
49
  def __init__(
48
50
  self,
49
51
  cache_type: CacheType,
50
- func: types.FunctionType,
52
+ func: FunctionType,
51
53
  arg_name: str | None,
52
54
  arg_value: Any,
53
55
  orig_exc: BaseException,
@@ -59,7 +61,7 @@ class UnhashableParamError(StreamlitAPIException):
59
61
  @staticmethod
60
62
  def _create_message(
61
63
  cache_type: CacheType,
62
- func: types.FunctionType,
64
+ func: FunctionType,
63
65
  arg_name: str | None,
64
66
  arg_value: Any,
65
67
  ) -> str:
@@ -96,7 +98,7 @@ class CacheReplayClosureError(StreamlitAPIException):
96
98
  def __init__(
97
99
  self,
98
100
  cache_type: CacheType,
99
- cached_func: types.FunctionType,
101
+ cached_func: FunctionType,
100
102
  ):
101
103
  func_name = get_cached_func_name_md(cached_func)
102
104
  decorator_name = get_decorator_api_name(cache_type)
@@ -118,7 +120,7 @@ How to fix this:
118
120
 
119
121
 
120
122
  class UnserializableReturnValueError(MarkdownFormattedException):
121
- def __init__(self, func: types.FunctionType, return_value: types.FunctionType):
123
+ def __init__(self, func: FunctionType, return_value: FunctionType):
122
124
  MarkdownFormattedException.__init__(
123
125
  self,
124
126
  f"""
@@ -19,8 +19,7 @@ from __future__ import annotations
19
19
  import math
20
20
  import threading
21
21
  import types
22
- from datetime import timedelta
23
- from typing import Any, Callable, Final, TypeVar, cast, overload
22
+ from typing import TYPE_CHECKING, Any, Callable, Final, TypeVar, cast, overload
24
23
 
25
24
  from cachetools import TTLCache
26
25
  from typing_extensions import TypeAlias
@@ -44,12 +43,16 @@ from streamlit.runtime.caching.cached_message_replay import (
44
43
  MultiCacheResults,
45
44
  show_widget_replay_deprecation,
46
45
  )
47
- from streamlit.runtime.caching.hashing import HashFuncsDict
48
46
  from streamlit.runtime.metrics_util import gather_metrics
49
47
  from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx
50
48
  from streamlit.runtime.stats import CacheStat, CacheStatsProvider, group_stats
51
49
  from streamlit.time_util import time_to_seconds
52
50
 
51
+ if TYPE_CHECKING:
52
+ from datetime import timedelta
53
+
54
+ from streamlit.runtime.caching.hashing import HashFuncsDict
55
+
53
56
  _LOGGER: Final = get_logger(__name__)
54
57
 
55
58
 
@@ -223,8 +226,7 @@ class CacheResourceAPI:
223
226
 
224
227
  # Bare decorator usage
225
228
  @overload
226
- def __call__(self, func: F) -> F:
227
- ...
229
+ def __call__(self, func: F) -> F: ...
228
230
 
229
231
  # Decorator with arguments
230
232
  @overload
@@ -237,8 +239,7 @@ class CacheResourceAPI:
237
239
  validate: ValidateFunc | None = None,
238
240
  experimental_allow_widgets: bool = False,
239
241
  hash_funcs: HashFuncsDict | None = None,
240
- ) -> Callable[[F], F]:
241
- ...
242
+ ) -> Callable[[F], F]: ...
242
243
 
243
244
  def __call__(
244
245
  self,
@@ -490,11 +491,11 @@ class ResourceCache(Cache):
490
491
 
491
492
  @property
492
493
  def max_entries(self) -> float:
493
- return cast(float, self._mem_cache.maxsize)
494
+ return self._mem_cache.maxsize
494
495
 
495
496
  @property
496
497
  def ttl_seconds(self) -> float:
497
- return cast(float, self._mem_cache.ttl)
498
+ return self._mem_cache.ttl
498
499
 
499
500
  def read_result(self, key: str) -> CachedResult:
500
501
  """Read a value and associated messages from the cache.
@@ -21,10 +21,9 @@ import hashlib
21
21
  import inspect
22
22
  import threading
23
23
  import time
24
- import types
25
24
  from abc import abstractmethod
26
25
  from collections import defaultdict
27
- from typing import Any, Callable, Final
26
+ from typing import TYPE_CHECKING, Any, Callable, Final
28
27
 
29
28
  from streamlit import type_util
30
29
  from streamlit.elements.spinner import spinner
@@ -38,7 +37,6 @@ from streamlit.runtime.caching.cache_errors import (
38
37
  UnserializableReturnValueError,
39
38
  get_cached_func_name_md,
40
39
  )
41
- from streamlit.runtime.caching.cache_type import CacheType
42
40
  from streamlit.runtime.caching.cached_message_replay import (
43
41
  CachedMessageReplayContext,
44
42
  CachedResult,
@@ -49,6 +47,11 @@ from streamlit.runtime.caching.hashing import HashFuncsDict, update_hash
49
47
  from streamlit.type_util import UNEVALUATED_DATAFRAME_TYPES
50
48
  from streamlit.util import HASHLIB_KWARGS
51
49
 
50
+ if TYPE_CHECKING:
51
+ from types import FunctionType
52
+
53
+ from streamlit.runtime.caching.cache_type import CacheType
54
+
52
55
  _LOGGER: Final = get_logger(__name__)
53
56
 
54
57
  # The timer function we use with TTLCache. This is the default timer func, but
@@ -120,7 +123,7 @@ class CachedFuncInfo:
120
123
 
121
124
  def __init__(
122
125
  self,
123
- func: types.FunctionType,
126
+ func: FunctionType,
124
127
  show_spinner: bool | str,
125
128
  allow_widgets: bool,
126
129
  hash_funcs: HashFuncsDict | None,
@@ -354,7 +357,7 @@ class CachedFunc:
354
357
 
355
358
  def _make_value_key(
356
359
  cache_type: CacheType,
357
- func: types.FunctionType,
360
+ func: FunctionType,
358
361
  func_args: tuple[Any, ...],
359
362
  func_kwargs: dict[str, Any],
360
363
  hash_funcs: HashFuncsDict | None,
@@ -419,7 +422,7 @@ def _make_value_key(
419
422
  return value_key
420
423
 
421
424
 
422
- def _make_function_key(cache_type: CacheType, func: types.FunctionType) -> str:
425
+ def _make_function_key(cache_type: CacheType, func: FunctionType) -> str:
423
426
  """Create the unique key for a function's cache.
424
427
 
425
428
  A function's key is stable across reruns of the app, and changes when
@@ -458,7 +461,7 @@ def _make_function_key(cache_type: CacheType, func: types.FunctionType) -> str:
458
461
  return cache_key
459
462
 
460
463
 
461
- def _get_positional_arg_name(func: types.FunctionType, arg_index: int) -> str | None:
464
+ def _get_positional_arg_name(func: FunctionType, arg_index: int) -> str | None:
462
465
  """Return the name of a function's positional argument.
463
466
 
464
467
  If arg_index is out of range, or refers to a parameter that is not a
@@ -17,28 +17,29 @@ from __future__ import annotations
17
17
  import contextlib
18
18
  import hashlib
19
19
  import threading
20
- import types
21
20
  from dataclasses import dataclass
22
21
  from typing import TYPE_CHECKING, Any, Iterator, Literal, Union
23
22
 
24
- from google.protobuf.message import Message
25
-
26
23
  import streamlit as st
27
24
  from streamlit import runtime, util
28
25
  from streamlit.deprecation_util import show_deprecation_warning
29
- from streamlit.proto.Block_pb2 import Block
30
26
  from streamlit.runtime.caching.cache_errors import CacheReplayClosureError
31
- from streamlit.runtime.caching.cache_type import CacheType
32
27
  from streamlit.runtime.caching.hashing import update_hash
33
28
  from streamlit.runtime.scriptrunner.script_run_context import (
34
29
  ScriptRunContext,
35
30
  get_script_run_ctx,
36
31
  )
37
- from streamlit.runtime.state.common import WidgetMetadata
38
32
  from streamlit.util import HASHLIB_KWARGS
39
33
 
40
34
  if TYPE_CHECKING:
35
+ from types import FunctionType
36
+
37
+ from google.protobuf.message import Message
38
+
41
39
  from streamlit.delta_generator import DeltaGenerator
40
+ from streamlit.proto.Block_pb2 import Block
41
+ from streamlit.runtime.caching.cache_type import CacheType
42
+ from streamlit.runtime.state.common import WidgetMetadata
42
43
 
43
44
 
44
45
  @dataclass(frozen=True)
@@ -233,7 +234,7 @@ class CachedMessageReplayContext(threading.local):
233
234
 
234
235
  @contextlib.contextmanager
235
236
  def calling_cached_function(
236
- self, func: types.FunctionType, allow_widgets: bool
237
+ self, func: FunctionType, allow_widgets: bool
237
238
  ) -> Iterator[None]:
238
239
  """Context manager that should wrap the invocation of a cached function.
239
240
  It allows us to track any `st.foo` messages that are generated from inside the function
@@ -364,7 +365,7 @@ class CachedMessageReplayContext(threading.local):
364
365
 
365
366
 
366
367
  def replay_cached_messages(
367
- result: CachedResult, cache_type: CacheType, cached_func: types.FunctionType
368
+ result: CachedResult, cache_type: CacheType, cached_func: FunctionType
368
369
  ) -> None:
369
370
  """Replay the st element function calls that happened when executing a
370
371
  cache-decorated function.
@@ -431,7 +432,7 @@ def _make_widget_key(widgets: list[tuple[str, Any]], cache_type: CacheType) -> s
431
432
 
432
433
 
433
434
  def show_widget_replay_deprecation(
434
- decorator: Literal["cache_data", "cache_resource"]
435
+ decorator: Literal["cache_data", "cache_resource"],
435
436
  ) -> None:
436
437
  show_deprecation_warning(
437
438
  "The `experimental_allow_widgets` parameter is deprecated and will be removed "
@@ -202,9 +202,9 @@ class _HashStacks:
202
202
  """Stacks of what has been hashed, with at most 1 stack per thread."""
203
203
 
204
204
  def __init__(self):
205
- self._stacks: weakref.WeakKeyDictionary[
206
- threading.Thread, _HashStack
207
- ] = weakref.WeakKeyDictionary()
205
+ self._stacks: weakref.WeakKeyDictionary[threading.Thread, _HashStack] = (
206
+ weakref.WeakKeyDictionary()
207
+ )
208
208
 
209
209
  def __repr__(self) -> str:
210
210
  return util.repr_(self)