streamlit-nightly 1.35.1.dev20240610__py2.py3-none-any.whl → 1.35.1.dev20240612__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 (121) 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 +36 -13
  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/proto/Block_pb2.py +24 -22
  56. streamlit/proto/Block_pb2.pyi +19 -1
  57. streamlit/runtime/app_session.py +7 -7
  58. streamlit/runtime/caching/__init__.py +9 -13
  59. streamlit/runtime/caching/cache_data_api.py +18 -7
  60. streamlit/runtime/caching/cache_errors.py +8 -6
  61. streamlit/runtime/caching/cache_resource_api.py +10 -9
  62. streamlit/runtime/caching/cache_utils.py +10 -7
  63. streamlit/runtime/caching/cached_message_replay.py +10 -9
  64. streamlit/runtime/caching/hashing.py +3 -3
  65. streamlit/runtime/caching/storage/cache_storage_protocol.py +1 -1
  66. streamlit/runtime/connection_factory.py +4 -2
  67. streamlit/runtime/credentials.py +11 -20
  68. streamlit/runtime/forward_msg_cache.py +10 -11
  69. streamlit/runtime/forward_msg_queue.py +6 -4
  70. streamlit/runtime/fragment.py +7 -9
  71. streamlit/runtime/media_file_manager.py +4 -4
  72. streamlit/runtime/memory_media_file_storage.py +7 -8
  73. streamlit/runtime/metrics_util.py +2 -4
  74. streamlit/runtime/pages_manager.py +41 -41
  75. streamlit/runtime/runtime.py +4 -4
  76. streamlit/runtime/runtime_util.py +7 -12
  77. streamlit/runtime/scriptrunner/magic.py +1 -1
  78. streamlit/runtime/scriptrunner/script_requests.py +4 -2
  79. streamlit/runtime/scriptrunner/script_run_context.py +15 -15
  80. streamlit/runtime/scriptrunner/script_runner.py +8 -8
  81. streamlit/runtime/secrets.py +3 -5
  82. streamlit/runtime/session_manager.py +8 -7
  83. streamlit/runtime/state/common.py +1 -1
  84. streamlit/runtime/state/query_params_proxy.py +5 -10
  85. streamlit/runtime/state/safe_session_state.py +8 -7
  86. streamlit/runtime/state/widgets.py +27 -27
  87. streamlit/runtime/stats.py +1 -1
  88. streamlit/runtime/uploaded_file_manager.py +4 -2
  89. streamlit/runtime/websocket_session_manager.py +6 -4
  90. streamlit/static/asset-manifest.json +3 -3
  91. streamlit/static/index.html +1 -1
  92. streamlit/static/static/js/{8492.8ad745d1.chunk.js → 4335.b492cdb7.chunk.js} +1 -1
  93. streamlit/static/static/js/main.0ebf040e.js +2 -0
  94. streamlit/string_util.py +1 -1
  95. streamlit/testing/v1/app_test.py +4 -2
  96. streamlit/testing/v1/element_tree.py +33 -37
  97. streamlit/testing/v1/local_script_runner.py +7 -7
  98. streamlit/time_util.py +2 -4
  99. streamlit/type_util.py +16 -29
  100. streamlit/user_info.py +4 -2
  101. streamlit/util.py +1 -1
  102. streamlit/watcher/event_based_path_watcher.py +6 -3
  103. streamlit/watcher/local_sources_watcher.py +11 -7
  104. streamlit/web/bootstrap.py +1 -1
  105. streamlit/web/cache_storage_manager_config.py +5 -1
  106. streamlit/web/cli.py +9 -4
  107. streamlit/web/server/browser_websocket_handler.py +7 -8
  108. streamlit/web/server/component_request_handler.py +4 -2
  109. streamlit/web/server/routes.py +3 -3
  110. streamlit/web/server/server.py +12 -12
  111. streamlit/web/server/server_util.py +5 -6
  112. streamlit/web/server/stats_request_handler.py +1 -1
  113. streamlit/web/server/upload_file_request_handler.py +5 -3
  114. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240612.dist-info}/METADATA +1 -1
  115. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240612.dist-info}/RECORD +120 -120
  116. streamlit/static/static/js/main.dc75074b.js +0 -2
  117. /streamlit/static/static/js/{main.dc75074b.js.LICENSE.txt → main.0ebf040e.js.LICENSE.txt} +0 -0
  118. {streamlit_nightly-1.35.1.dev20240610.data → streamlit_nightly-1.35.1.dev20240612.data}/scripts/streamlit.cmd +0 -0
  119. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240612.dist-info}/WHEEL +0 -0
  120. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240612.dist-info}/entry_points.txt +0 -0
  121. {streamlit_nightly-1.35.1.dev20240610.dist-info → streamlit_nightly-1.35.1.dev20240612.dist-info}/top_level.txt +0 -0
@@ -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)
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """ Declares the CacheStorageContext dataclass, which contains parameter information for
15
+ """Declares the CacheStorageContext dataclass, which contains parameter information for
16
16
  each function decorated by `@st.cache_data` (for example: ttl, max_entries etc.)
17
17
 
18
18
  Declares the CacheStorageManager protocol, which implementations are used
@@ -16,8 +16,7 @@ from __future__ import annotations
16
16
 
17
17
  import os
18
18
  import re
19
- from datetime import timedelta
20
- from typing import Any, Final, Literal, TypeVar, overload
19
+ from typing import TYPE_CHECKING, Any, Final, Literal, TypeVar, overload
21
20
 
22
21
  from streamlit.connections import (
23
22
  BaseConnection,
@@ -31,6 +30,9 @@ from streamlit.runtime.caching import cache_resource
31
30
  from streamlit.runtime.metrics_util import gather_metrics
32
31
  from streamlit.runtime.secrets import secrets_singleton
33
32
 
33
+ if TYPE_CHECKING:
34
+ from datetime import timedelta
35
+
34
36
  # NOTE: Adding support for a new first party connection requires:
35
37
  # 1. Adding the new connection name and class to this dict.
36
38
  # 2. Writing two new @overloads for connection_factory (one for the case where the
@@ -20,9 +20,8 @@ import json
20
20
  import os
21
21
  import sys
22
22
  import textwrap
23
- from collections import namedtuple
24
23
  from datetime import datetime
25
- from typing import Final, NoReturn
24
+ from typing import Final, NamedTuple, NoReturn
26
25
  from uuid import uuid4
27
26
 
28
27
  from streamlit import cli_util, env_util, file_util, util
@@ -36,13 +35,10 @@ if env_util.IS_WINDOWS:
36
35
  else:
37
36
  _CONFIG_FILE_PATH = "~/.streamlit/config.toml"
38
37
 
39
- _Activation = namedtuple(
40
- "_Activation",
41
- [
42
- "email", # str : the user's email.
43
- "is_valid", # boolean : whether the email is valid.
44
- ],
45
- )
38
+
39
+ class _Activation(NamedTuple):
40
+ email: str | None # the user's email.
41
+ is_valid: bool # whether the email is valid.
46
42
 
47
43
 
48
44
  def email_prompt() -> str:
@@ -55,19 +51,14 @@ def email_prompt() -> str:
55
51
  )
56
52
 
57
53
  # IMPORTANT: Break the text below at 80 chars.
58
- return """
59
- {0}%(welcome)s
54
+ return f"""
55
+ {"👋 " if show_emoji else ""}{cli_util.style_for_cli("Welcome to Streamlit!", bold=True)}
60
56
 
61
57
  If you’d like to receive helpful onboarding emails, news, offers, promotions,
62
58
  and the occasional swag, please enter your email address below. Otherwise,
63
59
  leave this field blank.
64
60
 
65
- %(email)s""".format(
66
- "👋 " if show_emoji else ""
67
- ) % {
68
- "welcome": cli_util.style_for_cli("Welcome to Streamlit!", bold=True),
69
- "email": cli_util.style_for_cli("Email: ", fg="blue"),
70
- }
61
+ {cli_util.style_for_cli("Email: ", fg="blue")}"""
71
62
 
72
63
 
73
64
  _TELEMETRY_HEADLESS_TEXT = """
@@ -119,10 +110,10 @@ def _send_email(email: str) -> None:
119
110
  response.raise_for_status()
120
111
 
121
112
 
122
- class Credentials(object):
113
+ class Credentials:
123
114
  """Credentials class."""
124
115
 
125
- _singleton: "Credentials" | None = None
116
+ _singleton: Credentials | None = None
126
117
 
127
118
  @classmethod
128
119
  def get_current(cls):
@@ -156,7 +147,7 @@ class Credentials(object):
156
147
  import toml
157
148
 
158
149
  try:
159
- with open(self._conf_file, "r") as f:
150
+ with open(self._conf_file) as f:
160
151
  data = toml.load(f).get("general")
161
152
  if data is None:
162
153
  raise Exception
@@ -111,9 +111,9 @@ class ForwardMsgCache(CacheStatsProvider):
111
111
 
112
112
  def __init__(self, msg: ForwardMsg | None):
113
113
  self.msg = msg
114
- self._session_script_run_counts: MutableMapping[
115
- AppSession, int
116
- ] = WeakKeyDictionary()
114
+ self._session_script_run_counts: MutableMapping[AppSession, int] = (
115
+ WeakKeyDictionary()
116
+ )
117
117
 
118
118
  def __repr__(self) -> str:
119
119
  return util.repr_(self)
@@ -285,13 +285,12 @@ class ForwardMsgCache(CacheStatsProvider):
285
285
  self._entries.clear()
286
286
 
287
287
  def get_stats(self) -> list[CacheStat]:
288
- stats: list[CacheStat] = []
289
- for entry_hash, entry in self._entries.items():
290
- stats.append(
291
- CacheStat(
292
- category_name="ForwardMessageCache",
293
- cache_name="",
294
- byte_length=entry.msg.ByteSize() if entry.msg is not None else 0,
295
- )
288
+ stats: list[CacheStat] = [
289
+ CacheStat(
290
+ category_name="ForwardMessageCache",
291
+ cache_name="",
292
+ byte_length=entry.msg.ByteSize() if entry.msg is not None else 0,
296
293
  )
294
+ for _, entry in self._entries.items()
295
+ ]
297
296
  return group_stats(stats)
@@ -14,11 +14,13 @@
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 streamlit.proto.Delta_pb2 import Delta
20
19
  from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
21
20
 
21
+ if TYPE_CHECKING:
22
+ from streamlit.proto.Delta_pb2 import Delta
23
+
22
24
 
23
25
  class ForwardMsgQueue:
24
26
  """Accumulates a session's outgoing ForwardMsgs.
@@ -38,7 +40,7 @@ class ForwardMsgQueue:
38
40
  # redundant outgoing Deltas (where a newer Delta supersedes
39
41
  # an older Delta, with the same delta_path, that's still in the
40
42
  # queue).
41
- self._delta_index_map: dict[tuple[int, ...], int] = dict()
43
+ self._delta_index_map: dict[tuple[int, ...], int] = {}
42
44
 
43
45
  def get_debug(self) -> dict[str, Any]:
44
46
  from google.protobuf.json_format import MessageToDict
@@ -102,7 +104,7 @@ class ForwardMsgQueue:
102
104
  }
103
105
  ]
104
106
 
105
- self._delta_index_map = dict()
107
+ self._delta_index_map = {}
106
108
 
107
109
  def flush(self) -> list[ForwardMsg]:
108
110
  """Clear the queue and return a list of the messages it contained
@@ -19,15 +19,17 @@ import hashlib
19
19
  import inspect
20
20
  from abc import abstractmethod
21
21
  from copy import deepcopy
22
- from datetime import timedelta
23
22
  from functools import wraps
24
- from typing import Any, Callable, Protocol, TypeVar, overload
23
+ from typing import TYPE_CHECKING, Any, Callable, Protocol, TypeVar, overload
25
24
 
26
25
  from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
27
26
  from streamlit.runtime.metrics_util import gather_metrics
28
27
  from streamlit.runtime.scriptrunner import get_script_run_ctx
29
28
  from streamlit.time_util import time_to_seconds
30
29
 
30
+ if TYPE_CHECKING:
31
+ from datetime import timedelta
32
+
31
33
  F = TypeVar("F", bound=Callable[..., Any])
32
34
  Fragment = Callable[[], Any]
33
35
 
@@ -127,9 +129,7 @@ def _fragment(
127
129
  active_dg = dg_stack_snapshot[-1]
128
130
  h = hashlib.new("md5")
129
131
  h.update(
130
- f"{non_optional_func.__module__}.{non_optional_func.__qualname__}{active_dg._get_delta_path_str()}".encode(
131
- "utf-8"
132
- )
132
+ f"{non_optional_func.__module__}.{non_optional_func.__qualname__}{active_dg._get_delta_path_str()}".encode()
133
133
  )
134
134
  fragment_id = h.hexdigest()
135
135
 
@@ -207,8 +207,7 @@ def fragment(
207
207
  func: F,
208
208
  *,
209
209
  run_every: int | float | timedelta | str | None = None,
210
- ) -> F:
211
- ...
210
+ ) -> F: ...
212
211
 
213
212
 
214
213
  # Support being able to pass parameters to this decorator (that is, being able to write
@@ -218,8 +217,7 @@ def fragment(
218
217
  func: None = None,
219
218
  *,
220
219
  run_every: int | float | timedelta | str | None = None,
221
- ) -> Callable[[F], F]:
222
- ...
220
+ ) -> Callable[[F], F]: ...
223
221
 
224
222
 
225
223
  @gather_metrics("experimental_fragment")
@@ -82,12 +82,12 @@ class MediaFileManager:
82
82
  self._storage = storage
83
83
 
84
84
  # Dict of [file_id -> MediaFileMetadata]
85
- self._file_metadata: dict[str, MediaFileMetadata] = dict()
85
+ self._file_metadata: dict[str, MediaFileMetadata] = {}
86
86
 
87
87
  # Dict[session ID][coordinates] -> file_id.
88
- self._files_by_session_and_coord: dict[
89
- str, dict[str, str]
90
- ] = collections.defaultdict(dict)
88
+ self._files_by_session_and_coord: dict[str, dict[str, str]] = (
89
+ collections.defaultdict(dict)
90
+ )
91
91
 
92
92
  # MediaFileManager is used from multiple threads, so all operations
93
93
  # need to be protected with a Lock. (This is not an RLock, which
@@ -171,13 +171,12 @@ class MemoryMediaFileStorage(MediaFileStorage, CacheStatsProvider):
171
171
  # with other threads that may be manipulating the cache.
172
172
  files_by_id = self._files_by_id.copy()
173
173
 
174
- stats: list[CacheStat] = []
175
- for file_id, file in files_by_id.items():
176
- stats.append(
177
- CacheStat(
178
- category_name="st_memory_media_file_storage",
179
- cache_name="",
180
- byte_length=len(file.content),
181
- )
174
+ stats: list[CacheStat] = [
175
+ CacheStat(
176
+ category_name="st_memory_media_file_storage",
177
+ cache_name="",
178
+ byte_length=len(file.content),
182
179
  )
180
+ for _, file in files_by_id.items()
181
+ ]
183
182
  return group_stats(stats)
@@ -306,16 +306,14 @@ F = TypeVar("F", bound=Callable[..., Any])
306
306
  def gather_metrics(
307
307
  name: str,
308
308
  func: F,
309
- ) -> F:
310
- ...
309
+ ) -> F: ...
311
310
 
312
311
 
313
312
  @overload
314
313
  def gather_metrics(
315
314
  name: str,
316
315
  func: None = None,
317
- ) -> Callable[[F], F]:
318
- ...
316
+ ) -> Callable[[F], F]: ...
319
317
 
320
318
 
321
319
  def gather_metrics(name: str, func: F | None = None) -> Callable[[F], F] | F: