flet 1.1.0.dev0__py3-none-any.whl → 1.1.0.dev2__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.
flet/app.py CHANGED
@@ -374,6 +374,14 @@ def __get_on_session_created(
374
374
  session: Active page session.
375
375
  """
376
376
 
377
+ def mark_test_ready():
378
+ # Registration precedes main(). Send readiness in a page patch only
379
+ # after main's initial updates, including for an intentionally empty
380
+ # app. Generator apps are ready after their first yielded update.
381
+ if session.page.test and not session.page._internals.get("test_ready"):
382
+ session.page._internals["test_ready"] = True
383
+ session.page.update()
384
+
377
385
  logger.info("App session started")
378
386
  try:
379
387
  assert main is not None
@@ -385,15 +393,18 @@ def __get_on_session_created(
385
393
  elif inspect.isasyncgenfunction(main):
386
394
  async for _ in main(session.page):
387
395
  await session.after_event(session.page)
396
+ mark_test_ready()
388
397
 
389
398
  elif inspect.isgeneratorfunction(main):
390
399
  for _ in main(session.page):
391
400
  await session.after_event(session.page)
401
+ mark_test_ready()
392
402
  else:
393
403
  # run synchronously
394
404
  main(session.page)
395
405
 
396
406
  await session.after_event(session.page)
407
+ mark_test_ready()
397
408
 
398
409
  except Exception as e:
399
410
  logger.error("Unhandled error in main() handler", exc_info=True)
@@ -341,7 +341,7 @@ class Component(BaseControl):
341
341
  or hook.deps != hook.prev_deps
342
342
  )
343
343
  if deps_changed:
344
- if callable(hook.cleanup):
344
+ if hook.has_cleanup():
345
345
  self._schedule_effect(hook, is_cleanup=True)
346
346
  self._schedule_effect(hook, is_cleanup=False)
347
347
 
@@ -354,7 +354,7 @@ class Component(BaseControl):
354
354
  logger.debug("%s._run_unmount_effects()", self)
355
355
  for hook in self._state.hooks:
356
356
  # all effects are running on unmount
357
- if isinstance(hook, EffectHook) and callable(hook.cleanup):
357
+ if isinstance(hook, EffectHook) and hook.has_lifecycle_work():
358
358
  self._schedule_effect(hook, is_cleanup=True)
359
359
  self._state.hooks.clear()
360
360
 
@@ -1,6 +1,6 @@
1
1
  import asyncio
2
2
  from collections.abc import Awaitable, Callable, Sequence
3
- from dataclasses import dataclass
3
+ from dataclasses import dataclass, field
4
4
  from typing import Any
5
5
 
6
6
  from flet.components.hooks.hook import Hook
@@ -20,23 +20,103 @@ class EffectHook(Hook):
20
20
 
21
21
  setup: Callable[[], Any | Awaitable[Any]]
22
22
  cleanup: Callable[[], Any | Awaitable[Any]] | None = None
23
+ _returned_cleanup: Callable[[], Any | Awaitable[Any]] | None = None
24
+ """The cleanup the last non-`async` setup run returned, if any."""
25
+
23
26
  deps: list[Any] | None = None
24
27
  prev_deps: list[Any] | None = None
25
28
 
26
- # runtime
27
- _setup_task: asyncio.Task | None = None # last scheduled setup task
28
- _cleanup_task: asyncio.Task | None = None # last scheduled cleanup task
29
+ _setup_task: asyncio.Task | None = None
30
+ """The task running the last `async` setup, cancelled when the effect re-runs or
31
+ the component unmounts."""
32
+
33
+ _cleanup_task: asyncio.Task | None = None
34
+ """The task finishing the effect's last cleanups, when one of them is `async`.
35
+ Until it has finished and the effect's waiting setups and cleanups have run,
36
+ new ones wait in `_queued`."""
37
+
38
+ _queued: list[Callable[[], Any | Awaitable[Any]] | None] = field(
39
+ default_factory=list
40
+ )
41
+ """Setups and cleanups waiting for `_cleanup_task`, in the order they were
42
+ scheduled: a setup as the setup function it was scheduled with, a cleanup as
43
+ `None`."""
44
+
45
+ _active: bool = False
46
+ """Whether a setup has run since the last cleanup, so there is something to
47
+ clean up."""
48
+
49
+ def has_cleanup(self) -> bool:
50
+ """
51
+ Whether the effect has a cleanup to run: one its setup returned, the
52
+ `cleanup` argument, or both.
53
+ """
54
+ return callable(self._returned_cleanup) or callable(self.cleanup)
55
+
56
+ def has_lifecycle_work(self) -> bool:
57
+ """
58
+ Whether unmounting has work to do: a cleanup to run, or a setup task still
59
+ running to cancel.
60
+ """
61
+ return self.has_cleanup() or (
62
+ self._setup_task is not None and not self._setup_task.done()
63
+ )
64
+
65
+ def take_cleanups(self) -> list[Callable[[], Any | Awaitable[Any]]]:
66
+ """
67
+ Returns the cleanups to run, in order: the one the last setup returned, then
68
+ the `cleanup` argument.
69
+
70
+ The returned cleanup belongs to the setup run that returned it, so it is
71
+ forgotten here and runs only once.
72
+ """
73
+ cleanups = [c for c in (self._returned_cleanup, self.cleanup) if callable(c)]
74
+ self._returned_cleanup = None
75
+ return cleanups
76
+
77
+ def running_cleanup(self) -> asyncio.Task | None:
78
+ """
79
+ Returns the task finishing the effect's last cleanups, until it has finished
80
+ and the setups and cleanups waiting for it have run.
81
+ """
82
+ return self._cleanup_task
29
83
 
30
- def cancel(self):
84
+ def is_live(self) -> bool:
85
+ """
86
+ Whether the effect still belongs to a mounted component: it hasn't unmounted
87
+ and hasn't been replaced by a remount.
31
88
  """
32
- Cancels currently scheduled setup and cleanup tasks, if still pending.
89
+ component = self.component
90
+ return (
91
+ component is not None
92
+ and component._state.mounted
93
+ and self in component._state.hooks
94
+ )
33
95
 
34
- Safe to call repeatedly; completed tasks are ignored.
96
+ def take_queued(self) -> list[Callable[[], Any | Awaitable[Any]] | None]:
97
+ """
98
+ Returns what to run of the setups and cleanups that waited for the effect's
99
+ cleanups, in `_queued`'s form: one cleanup if any was queued, then the last
100
+ setup if it came last. Earlier setups never ran and were superseded, so
101
+ there is nothing to run them for. No setup is returned once the effect
102
+ isn't live (see `is_live()`).
103
+ """
104
+ queued, self._queued = self._queued, []
105
+ ops: list[Callable[[], Any | Awaitable[Any]] | None] = []
106
+ if any(op is None for op in queued):
107
+ ops.append(None)
108
+ if queued and queued[-1] is not None and self.is_live():
109
+ ops.append(queued[-1])
110
+ return ops
111
+
112
+ def cancel_setup(self):
113
+ """
114
+ Cancels the last setup task, if it is still running.
115
+
116
+ A running cleanup task is left to finish. Safe to call repeatedly.
35
117
  """
36
118
  if self._setup_task and not self._setup_task.done():
37
119
  self._setup_task.cancel()
38
- if self._cleanup_task and not self._cleanup_task.done():
39
- self._cleanup_task.cancel()
40
120
 
41
121
 
42
122
  def use_effect(
@@ -45,17 +125,56 @@ def use_effect(
45
125
  cleanup: Callable[[], Any | Awaitable[Any]] | None = None,
46
126
  ):
47
127
  """
48
- Perform side effects in function components.
128
+ Runs a side effect, such as starting a timer or opening a connection, after the
129
+ component renders, and cleans it up when it is no longer needed.
130
+
131
+ The setup runs after the component mounts, then again after each render that
132
+ `dependencies` selects. Before it runs again, and when the component unmounts,
133
+ the effect's cleanups run: the cleanup the setup returned, then `cleanup`. They
134
+ run once for each time the setup ran, and always finish, in order, before the
135
+ setup runs again, even when one of them is `async`.
136
+
137
+ A cleanup the setup returns belongs to that setup run, so it sees the same
138
+ values the setup saw. `cleanup` is the function the latest render passed, so it
139
+ sees that render's values. Returning the cleanup from the setup is usually what
140
+ you want.
49
141
 
50
142
  Args:
51
- setup: A function that performs the side effect. It may optionally return
52
- a cleanup function.
143
+ setup: A function that performs the side effect. It may be `async`. A
144
+ non-`async` setup may return a cleanup function. An `async` setup's
145
+ return value is not used: pass `cleanup` instead. An `async` setup still
146
+ running when the effect re-runs or the component unmounts is cancelled.
53
147
  dependencies: Values the effect depends on. The effect always runs after the
54
148
  component mounts. If absent, it also re-runs after every render. If
55
149
  empty, it runs only on mount. Otherwise, it re-runs only when one of the
56
150
  dependencies has changed.
57
- cleanup: An optional function that cleans up after the effect. It is run
58
- before the effect is re-run, and when the component unmounts.
151
+ cleanup: A function that cleans up after the effect, run after the cleanup
152
+ the setup returned. It may be `async`.
153
+
154
+ Example:
155
+ ```python
156
+ import asyncio
157
+ from datetime import datetime
158
+
159
+ import flet as ft
160
+
161
+
162
+ @ft.component
163
+ def Clock():
164
+ now, set_now = ft.use_state(datetime.now())
165
+
166
+ def start_ticking():
167
+ async def tick():
168
+ while True:
169
+ await asyncio.sleep(1)
170
+ set_now(datetime.now())
171
+
172
+ task = asyncio.create_task(tick())
173
+ return task.cancel # stops ticking when Clock unmounts
174
+
175
+ ft.use_effect(start_ticking, [])
176
+ return ft.Text(f"{now:%H:%M:%S}")
177
+ ```
59
178
  """
60
179
  component = current_component()
61
180
  deps = list(dependencies) if dependencies is not None else None
@@ -79,24 +198,21 @@ def use_effect(
79
198
 
80
199
  def on_mounted(fn: Callable[[], Any | Awaitable[Any]]) -> None:
81
200
  """
82
- Run exactly once after the component mounts.
201
+ Runs `fn` once, after the component mounts.
83
202
 
84
203
  Args:
85
- fn (Callable[[], Any | Awaitable[Any]]): A function to run after the component
86
- mounts.
204
+ fn: The function to run. It may be `async`.
87
205
  """
88
206
  use_effect(fn, dependencies=[])
89
207
 
90
208
 
91
209
  def on_unmounted(fn: Callable[[], Any | Awaitable[Any]]) -> None:
92
210
  """
93
- Run exactly once when the component unmounts.
211
+ Runs `fn` once, when the component unmounts.
94
212
 
95
213
  Args:
96
- fn (Callable[[], Any | Awaitable[Any]]): A function to run when the component
97
- unmounts.
214
+ fn: The function to run. It may be `async`.
98
215
  """
99
- # No-op setup; only need cleanup to fire on unmount
100
216
  use_effect(lambda: None, dependencies=[], cleanup=fn)
101
217
 
102
218
 
@@ -104,16 +220,14 @@ def on_updated(
104
220
  fn: Callable[[], Any | Awaitable[Any]], dependencies: Sequence[Any] | None = None
105
221
  ) -> None:
106
222
  """
107
- Run after each post-mount render (or when dependencies change).
108
- With dependencies=None this fires every update; with dependencies=[...] only
109
- on changes.
223
+ Runs `fn` after the component mounts, then again after each render that
224
+ `dependencies` selects.
110
225
 
111
226
  Args:
112
- fn (Callable[[], Any | Awaitable[Any]]): A function to run after each
113
- post-mount render (or when dependencies change).
114
- dependencies (Sequence[Any] | None): If present, `fn` is only run when one
115
- of the dependencies has changed. If absent, `fn` is run after every
116
- render.
227
+ fn: The function to run. It may be `async`.
228
+ dependencies: Values `fn` depends on. If absent, `fn` re-runs after every
229
+ render. Otherwise, it re-runs only when one of the dependencies has
230
+ changed.
117
231
  """
118
232
  use_effect(fn, dependencies=dependencies)
119
233
 
flet/controls/page.py CHANGED
@@ -4,8 +4,8 @@ import logging
4
4
  import sys
5
5
  import threading
6
6
  import weakref
7
- from collections.abc import Awaitable, Coroutine
8
- from concurrent.futures import CancelledError, Future, ThreadPoolExecutor
7
+ from collections.abc import Awaitable, Coroutine, Generator
8
+ from concurrent.futures import Future, ThreadPoolExecutor
9
9
  from dataclasses import InitVar, dataclass, field, fields, is_dataclass
10
10
  from functools import partial
11
11
  from typing import (
@@ -16,6 +16,7 @@ from typing import (
16
16
  Optional,
17
17
  ParamSpec,
18
18
  TypeVar,
19
+ cast,
19
20
  )
20
21
  from urllib.parse import urlparse
21
22
 
@@ -91,6 +92,26 @@ InputT = ParamSpec("InputT")
91
92
  RetT = TypeVar("RetT")
92
93
 
93
94
 
95
+ class TaskFuture(Future[RetT]):
96
+ """
97
+ The future of a task started with `Page.run_task()`.
98
+
99
+ It is a `concurrent.futures.Future` that can also be awaited, from the page's
100
+ event loop or any other one: `await` returns the task's value or raises its
101
+ exception. Awaiting doesn't consume it: the outcome stays available through
102
+ `result()` and `exception()`.
103
+
104
+ Cancelling the coroutine that awaits it also cancels the task, as with an
105
+ `asyncio.Task`; await `asyncio.shield()` of it to keep the task running.
106
+ `result()` blocks, so call it on the page's event loop thread only once the
107
+ task is done.
108
+ """
109
+
110
+ def __await__(self) -> Generator[Any, None, RetT]:
111
+ """Wait for the task to finish without blocking the event loop."""
112
+ return asyncio.wrap_future(self).__await__()
113
+
114
+
94
115
  @control("ServiceRegistry")
95
116
  class ServiceRegistry(Service):
96
117
  """
@@ -943,10 +964,33 @@ class Page(BasePage):
943
964
  handler: Callable[InputT, Awaitable[RetT]],
944
965
  *args: InputT.args,
945
966
  **kwargs: InputT.kwargs,
946
- ) -> Future[RetT]:
967
+ ) -> TaskFuture[RetT]:
947
968
  """
948
969
  Run `handler` coroutine as a new Task in the event loop associated with the \
949
970
  current page.
971
+
972
+ Can be called from any thread.
973
+
974
+ Args:
975
+ handler: The coroutine function to run.
976
+ *args: Positional arguments to call `handler` with.
977
+ **kwargs: Keyword arguments to call `handler` with.
978
+
979
+ Returns:
980
+ A future of the task. Awaiting it returns the value of `handler`, or
981
+ raises its exception. The future keeps that outcome, so keep a
982
+ reference to it to call `cancel()`, `result()` or
983
+ `add_done_callback()` later.
984
+
985
+ Raises:
986
+ TypeError: If `handler` is not a coroutine function.
987
+
988
+ Example:
989
+ ```python
990
+ future = page.run_task(fetch_users)
991
+ users = await future # the value, not a future
992
+ future.result() # the same value, without blocking
993
+ ```
950
994
  """
951
995
  _context_page.set(self)
952
996
  if not inspect.iscoroutinefunction(handler):
@@ -955,25 +999,31 @@ class Page(BasePage):
955
999
  future = asyncio.run_coroutine_threadsafe(
956
1000
  handler(*args, **kwargs), self.session.connection.loop
957
1001
  )
1002
+ future.__class__ = TaskFuture
958
1003
 
959
1004
  def _on_completion(f):
960
1005
  """
961
- Surface background task exceptions to default error handling.
1006
+ Log the exception of a task nobody awaits.
1007
+
1008
+ `concurrent.futures` logs an `Exception` raised from a done callback
1009
+ and runs the next one. The task's outcome is stored on the future
1010
+ and reaches awaiters through their own callback, so raising here is
1011
+ only for the log. A `BaseException` is not re-raised: it would skip
1012
+ the remaining callbacks and leave awaiters waiting forever.
962
1013
 
963
1014
  Args:
964
1015
  f: Completed future returned by `run_coroutine_threadsafe()`.
965
1016
  """
966
1017
 
967
- try:
968
- exception = f.exception()
969
- if exception:
970
- raise exception
971
- except CancelledError:
972
- pass
1018
+ if f.cancelled():
1019
+ return
1020
+ exception = f.exception()
1021
+ if isinstance(exception, Exception):
1022
+ raise exception
973
1023
 
974
1024
  future.add_done_callback(_on_completion)
975
1025
 
976
- return future
1026
+ return cast(TaskFuture[RetT], future)
977
1027
 
978
1028
  def __context_wrapper(self, handler: Callable[..., Any]) -> Wrapper:
979
1029
  """
@@ -272,7 +272,6 @@ class FilePicker(Service):
272
272
  "dialog_title": dialog_title,
273
273
  "initial_directory": initial_directory,
274
274
  },
275
- timeout=3600,
276
275
  )
277
276
 
278
277
  async def save_file(
@@ -291,7 +290,8 @@ class FilePicker(Service):
291
290
  Note:
292
291
  - On desktop, this method opens a dialog for the user to select a
293
292
  location and file name. If `src_bytes` is provided, those bytes
294
- are written to the selected file.
293
+ are written to the selected file; otherwise the file is created
294
+ empty, for the app to write to the returned path.
295
295
 
296
296
  Args:
297
297
  dialog_title: The title of the dialog window.
@@ -327,7 +327,6 @@ class FilePicker(Service):
327
327
  "allowed_extensions": allowed_extensions,
328
328
  "src_bytes": src_bytes,
329
329
  },
330
- timeout=3600,
331
330
  )
332
331
 
333
332
  async def pick_files(
@@ -387,7 +386,6 @@ class FilePicker(Service):
387
386
  "compression_quality": compression_quality,
388
387
  "cancel_upload_on_window_blur": cancel_upload_on_window_blur,
389
388
  },
390
- timeout=3600,
391
389
  )
392
390
  return [FilePickerFile(**self._normalize_file(file)) for file in files]
393
391
 
flet/messaging/session.py CHANGED
@@ -4,6 +4,7 @@ import inspect
4
4
  import logging
5
5
  import traceback
6
6
  import weakref
7
+ from collections.abc import Awaitable, Callable
7
8
  from datetime import datetime, timedelta, timezone
8
9
  from typing import TYPE_CHECKING, Any, Optional
9
10
 
@@ -60,7 +61,12 @@ class Session:
60
61
  self.__method_call_results: dict[asyncio.Event, tuple[Any, Optional[str]]] = {}
61
62
  self.__updates_ready: asyncio.Event = asyncio.Event()
62
63
  self.__pending_updates: set[BaseControl] = set()
63
- self.__pending_effects: list[tuple[weakref.ref[EffectHook], bool]] = []
64
+ self.__pending_effects: list[
65
+ tuple[EffectHook, Callable[[], Any | Awaitable[Any]] | None]
66
+ ] = []
67
+ self.__effect_cleanup_tasks: set[asyncio.Task] = set()
68
+ """Tasks awaiting `async` effect cleanups, held until they finish so they
69
+ aren't garbage collected while pending."""
64
70
  self.__updates_task: Optional[asyncio.Task] = None
65
71
  self.__closed = False
66
72
  # Whether this session's app renders via the declarative components
@@ -707,7 +713,7 @@ class Session:
707
713
  # Hold a strong reference to the hook until it runs. A weakref would
708
714
  # get cleared when the owning component unmounts and clears
709
715
  # `_state.hooks` — dropping queued cleanup effects on the floor.
710
- self.__pending_effects.append((hook, is_cleanup))
716
+ self.__pending_effects.append((hook, None if is_cleanup else hook.setup))
711
717
  self.__updates_ready.set()
712
718
 
713
719
  def start_updates_scheduler(self):
@@ -743,28 +749,139 @@ class Session:
743
749
  pending_effects = list(self.__pending_effects)
744
750
  self.__pending_effects.clear()
745
751
 
746
- for effect in pending_effects:
747
- try:
748
- hook = effect[0]
749
- is_cleanup = effect[1]
750
- # print(f"**** Running effect: {hook} {is_cleanup}")
751
- if hook and hook.setup and not is_cleanup:
752
- hook.cancel()
753
- res = None
754
- if inspect.iscoroutinefunction(hook.setup):
755
- hook._setup_task = asyncio.create_task(hook.setup())
756
- else:
757
- res = hook.setup()
758
- if callable(res):
759
- hook.cleanup = res
760
- elif hook and hook.cleanup and is_cleanup:
761
- hook.cancel()
762
- if inspect.iscoroutinefunction(hook.cleanup):
763
- hook._cleanup_task = asyncio.create_task(hook.cleanup())
764
- else:
765
- hook.cleanup()
766
- except Exception as ex:
767
- tb = traceback.format_exc()
768
- self.error(f"Exception in effect: {ex}\n{tb}")
752
+ for hook, setup in pending_effects:
753
+ if hook:
754
+ self.__run_effect(hook, setup)
769
755
  except asyncio.CancelledError:
770
756
  pass
757
+
758
+ def __run_effect(
759
+ self, hook: "EffectHook", setup: Callable[[], Any | Awaitable[Any]] | None
760
+ ):
761
+ """
762
+ Runs an effect's `setup`, the setup function it was scheduled with, or its
763
+ cleanups when `setup` is `None`. Queues it while the effect's previous
764
+ cleanups are still finishing.
765
+
766
+ Cleanups run only if a setup ran since the last ones, and always before the
767
+ next setup, even when that setup was scheduled without them. A setup that
768
+ runs after its component unmounted is cleaned up right away. A
769
+ `CancelledError` the effect raises itself means it was cancelled, which
770
+ isn't an error: running an effect never awaits, so it can't come from the
771
+ scheduler being cancelled. Other errors are reported.
772
+ """
773
+ try:
774
+ if hook.running_cleanup():
775
+ hook._queued.append(setup)
776
+ return
777
+ hook.cancel_setup()
778
+ if hook._active and (setup is None or hook.has_cleanup()):
779
+ hook._active = False
780
+ self.__run_effect_cleanups(hook, hook.take_cleanups())
781
+ if hook.running_cleanup() and setup is not None:
782
+ hook._queued.append(setup)
783
+ return
784
+ if setup is not None:
785
+ hook._active = True
786
+ if inspect.iscoroutinefunction(setup):
787
+ hook._setup_task = asyncio.create_task(setup())
788
+ else:
789
+ res = setup()
790
+ hook._returned_cleanup = res if callable(res) else None
791
+ if not hook.is_live():
792
+ hook.cancel_setup()
793
+ hook._active = False
794
+ self.__run_effect_cleanups(hook, hook.take_cleanups())
795
+ except asyncio.CancelledError:
796
+ pass
797
+ except Exception as ex:
798
+ self.__report_effect_error(ex)
799
+
800
+ def __run_effect_cleanups(
801
+ self,
802
+ hook: "EffectHook",
803
+ cleanups: list[Callable[[], Any | Awaitable[Any]]],
804
+ ):
805
+ """
806
+ Runs an effect's cleanups in order.
807
+
808
+ Non-`async` cleanups run right away, up to the first `async` one. That one
809
+ and the rest are finished in a task. Until it finishes, the effect's next
810
+ setups and cleanups wait. Then they run right away, before anything
811
+ scheduled later, unless the session has closed or disconnected.
812
+ """
813
+ started = None
814
+ for i, cleanup in enumerate(cleanups):
815
+ if inspect.iscoroutinefunction(cleanup):
816
+ break
817
+ started = self.__call_effect_cleanup(cleanup)
818
+ if started is not None:
819
+ i += 1
820
+ break
821
+ else:
822
+ return
823
+ task = asyncio.create_task(self.__finish_effect_cleanups(cleanups[i:], started))
824
+ hook._cleanup_task = task
825
+ self.__effect_cleanup_tasks.add(task)
826
+
827
+ def done(task: asyncio.Task):
828
+ self.__effect_cleanup_tasks.discard(task)
829
+ hook._cleanup_task = None
830
+ queued = hook.take_queued()
831
+ if self.__closed or (self.__conn is None and self.__expires_at is not None):
832
+ return
833
+ for setup in queued:
834
+ self.__run_effect(hook, setup)
835
+
836
+ task.add_done_callback(done)
837
+
838
+ def __call_effect_cleanup(
839
+ self, cleanup: Callable[[], Any | Awaitable[Any]]
840
+ ) -> Awaitable[Any] | None:
841
+ """
842
+ Calls a cleanup and returns what it returned if that is awaitable.
843
+
844
+ A cleanup that raises is reported; one that raises `CancelledError` was
845
+ cancelled, which isn't an error.
846
+ """
847
+ try:
848
+ res = cleanup()
849
+ return res if inspect.isawaitable(res) else None
850
+ except asyncio.CancelledError:
851
+ return None
852
+ except Exception as ex:
853
+ self.__report_effect_error(ex)
854
+ return None
855
+
856
+ async def __finish_effect_cleanups(
857
+ self,
858
+ cleanups: list[Callable[[], Any | Awaitable[Any]]],
859
+ started: Awaitable[Any] | None,
860
+ ):
861
+ """
862
+ Finishes an effect's cleanups in order: awaits `started`, then calls and
863
+ awaits each of `cleanups`.
864
+
865
+ One that raises is reported, and one that raises or is cancelled doesn't
866
+ keep the others from running. If this task itself is cancelled, the
867
+ cleanups not reached are skipped. Telling that apart from a cleanup
868
+ cancelled on its own needs `Task.cancelling()`, so on Python 3.10 they
869
+ still run.
870
+ """
871
+ pending = [started] if started is not None else []
872
+ for item in pending + cleanups:
873
+ try:
874
+ res = item if inspect.isawaitable(item) else item()
875
+ if inspect.isawaitable(res):
876
+ await res
877
+ except asyncio.CancelledError:
878
+ task = asyncio.current_task()
879
+ if task is not None and getattr(task, "cancelling", lambda: 0)():
880
+ raise
881
+ except Exception as ex:
882
+ self.__report_effect_error(ex)
883
+
884
+ def __report_effect_error(self, ex: Exception):
885
+ """Reports an exception raised by an effect setup or cleanup."""
886
+ tb = "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))
887
+ self.error(f"Exception in effect: {ex}\n{tb}")
flet/utils/validation.py CHANGED
@@ -20,6 +20,7 @@ The public entry points are:
20
20
  """
21
21
 
22
22
  import sys
23
+ import types
23
24
  from collections.abc import Iterable
24
25
  from dataclasses import dataclass
25
26
  from functools import cache
@@ -1635,19 +1636,18 @@ def _strip_annotated(annotation: Any) -> Any:
1635
1636
 
1636
1637
  def _annotation_allows_none(annotation: Any) -> bool:
1637
1638
  """
1638
- Return `True` if annotation contains `None` (for example `Optional[T]`).
1639
+ Return `True` if annotation contains `None`, as in `Optional[T]` or `T | None`.
1639
1640
 
1640
1641
  Args:
1641
1642
  annotation: Annotation to inspect.
1642
1643
 
1643
1644
  Returns:
1644
- `True` when the normalized annotation is a `Union[...]` containing
1645
- `NoneType`.
1645
+ `True` when the normalized annotation is a union containing `NoneType`.
1646
1646
  """
1647
1647
 
1648
1648
  annotation = _strip_annotated(annotation)
1649
1649
  origin = get_origin(annotation)
1650
- if origin is Union:
1650
+ if origin is Union or origin is types.UnionType:
1651
1651
  return any(arg is type(None) for arg in get_args(annotation))
1652
1652
  return False
1653
1653
 
flet/version.py CHANGED
@@ -16,7 +16,7 @@ __all__ = [
16
16
  ]
17
17
 
18
18
  # set by CI
19
- flet_version = "1.1.0.dev0"
19
+ flet_version = "1.1.0.dev2"
20
20
  """
21
21
  The Flet version in use.
22
22
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flet
3
- Version: 1.1.0.dev0
3
+ Version: 1.1.0.dev2
4
4
  Summary: Flet for Python - easily build interactive multi-platform apps in Python
5
5
  Author-email: "Appveyor Systems Inc." <hello@flet.dev>
6
6
  License-Expression: Apache-2.0
@@ -9,23 +9,23 @@ Project-URL: Repository, https://github.com/flet-dev/flet
9
9
  Project-URL: Documentation, https://flet.dev/docs/
10
10
  Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
- Requires-Dist: flet-cli==1.1.0.dev0; extra == "cli"
13
- Requires-Dist: flet-web==1.1.0.dev0; extra == "web"
12
+ Requires-Dist: flet-cli==1.1.0.dev2; extra == "cli"
13
+ Requires-Dist: flet-web==1.1.0.dev2; extra == "web"
14
14
  Requires-Dist: oauthlib>=3.2.2; platform_system != "Emscripten"
15
15
  Requires-Dist: httpx>=0.28.1; platform_system != "Emscripten"
16
16
  Requires-Dist: repath>=0.9.0
17
17
  Requires-Dist: msgpack>=1.1.0
18
18
  Requires-Dist: typing-extensions; python_version < "3.11"
19
19
  Provides-Extra: all
20
- Requires-Dist: flet-cli==1.1.0.dev0; extra == "all"
21
- Requires-Dist: flet-web==1.1.0.dev0; extra == "all"
22
- Requires-Dist: flet-desktop==1.1.0.dev0; extra == "all"
20
+ Requires-Dist: flet-cli==1.1.0.dev2; extra == "all"
21
+ Requires-Dist: flet-web==1.1.0.dev2; extra == "all"
22
+ Requires-Dist: flet-desktop==1.1.0.dev2; extra == "all"
23
23
  Provides-Extra: cli
24
- Requires-Dist: flet-cli==1.1.0.dev0; extra == "cli"
24
+ Requires-Dist: flet-cli==1.1.0.dev2; extra == "cli"
25
25
  Provides-Extra: desktop
26
- Requires-Dist: flet-desktop==1.1.0.dev0; extra == "desktop"
26
+ Requires-Dist: flet-desktop==1.1.0.dev2; extra == "desktop"
27
27
  Provides-Extra: web
28
- Requires-Dist: flet-web==1.1.0.dev0; extra == "web"
28
+ Requires-Dist: flet-web==1.1.0.dev2; extra == "web"
29
29
  Provides-Extra: test
30
30
  Requires-Dist: pytest>=7.2.0; extra == "test"
31
31
  Requires-Dist: pytest-asyncio>=1.1.0; extra == "test"
@@ -1,10 +1,10 @@
1
1
  flet/__init__.py,sha256=zPNGKVSGH_p6PddyB8rA9WYeKH43BhhBqHfCpevbzsc,64517
2
- flet/app.py,sha256=q8K9cFklfKvEiqkurccFmRfw9_uyGvYZJDZBWjNUzpc,26345
2
+ flet/app.py,sha256=B5E2nyrNQf5Ckr_YF4hpEjP_aY0rBgD0wKVWh8WbaWU,26905
3
3
  flet/cli.py,sha256=IUM25fY_sqMtl0hlQGhlMQaBb1oNyO0VZeeBgRodhuA,204
4
4
  flet/data_channel.py,sha256=B1m_DT_jCRry8ebv5NLNySMG_BPRwdiisveYQX5HHvY,5429
5
5
  flet/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
6
  flet/pytest_plugin.py,sha256=jjo8Hs7gjn22UCxNh9AGxOTQET9-wuhIXiYzQoofIKQ,5865
7
- flet/version.py,sha256=IUvjg4noP2FjxG-Baoa20MwpifTd_Qgukxs1ms6HqYw,4377
7
+ flet/version.py,sha256=Lt9F3pdUqkJwdJFrvMq1tgedcjqXsSDSMcbCUAGP3QU,4377
8
8
  flet/auth/__init__.py,sha256=8j9E6YuBwstGxwxWi1xKm0ZPkYBEU5SJzeriNsulQ1s,1608
9
9
  flet/auth/authorization.py,sha256=EBXt5dFe8mEi2c6PAsfoP7qdc-SDV6w1SzGXpEvUjac,1353
10
10
  flet/auth/authorization_service.py,sha256=akoDgthUrE0pf0XWWyNCtlBDttl1lfQ87Pt0gibLPTw,9701
@@ -19,7 +19,7 @@ flet/auth/providers/github_oauth_provider.py,sha256=SOfXQo8ATHc9Fww35rqahnTudumN
19
19
  flet/auth/providers/google_oauth_provider.py,sha256=HV5DWfjUP0wOMoWTxytWXlDqtrTZD5A9PhD3RN0x3U8,1035
20
20
  flet/canvas/__init__.py,sha256=_02Qjscc6DU4c4FYVSjv2S35ld6WFte_Be8NBABRN8Q,957
21
21
  flet/components/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- flet/components/component.py,sha256=3exgbnEKQP6NiYrcw4Tdco27x5mAhPyGKV_Gjd7Tvr4,17733
22
+ flet/components/component.py,sha256=3eMVLG-EA2gEj1kBR3dSk_6uBgufNpGyrKfv1qa9Bck,17732
23
23
  flet/components/component_decorator.py,sha256=wUxJhbbMbawB0TW2UTkBOOvwkgYe8zYBswQ-bJlUsuw,933
24
24
  flet/components/component_owned.py,sha256=Iuwid1TTu7KhCeaucaArKXNJ1h4Fmp200nmNKMl7Ebc,1543
25
25
  flet/components/memo.py,sha256=vx-1a9NKfc12M9uxeVRkI9ao4et3CX48Tld17tzMHy4,739
@@ -32,7 +32,7 @@ flet/components/hooks/hook.py,sha256=OfEuViUKRZWFKgVi-p511aT40RcRV59DnzjuUB_Nc7E
32
32
  flet/components/hooks/use_callback.py,sha256=v9R4igPXCzIOtvaadL1QLBPHZqVYW9hoRWd6gkDSXxk,937
33
33
  flet/components/hooks/use_context.py,sha256=TL8S8_rOjx8a2sZ_tQkTikrvYqpk-CQWgoc_gKKG9j0,3312
34
34
  flet/components/hooks/use_dialog.py,sha256=H2TThbgjg74GebgWovr7lQuljPLpiW6U1xVbGJtYSec,7619
35
- flet/components/hooks/use_effect.py,sha256=51o1oRNXrhhGB3_-t5AXgTekn0VnYB54W9ne_xZCgNw,4013
35
+ flet/components/hooks/use_effect.py,sha256=ck3-tDvmwm-5D5JhSAIktuLrfeQJJ5u4vP-tEj6DBhA,8420
36
36
  flet/components/hooks/use_memo.py,sha256=3Qc-nIsH0slVP1R1s1zuY-CwjCp3RYRFpj_KCi0L2l0,2392
37
37
  flet/components/hooks/use_ref.py,sha256=J26qFc0JexFgjOET2sqMHFFX86z6xG5dRfQvuxOr-bM,1948
38
38
  flet/components/hooks/use_state.py,sha256=R4v0PdiYTVuOr8zoMn2A8p97TvpN4xQK53w8RAWuShE,3594
@@ -71,7 +71,7 @@ flet/controls/multi_view.py,sha256=1mjn9Vusg2kMiRF8UksYxb9joXSeJKEUW4LpFwrPXck,6
71
71
  flet/controls/object_patch.py,sha256=mPv5HE1VzCgtrDas_Y3hJG8n07iNJ1DfoGPF9p_mPhg,72614
72
72
  flet/controls/package_info.py,sha256=WDkUELz8wwyjUhuncXcgY2x1KcUWdOBEAPatWNoLvXY,4195
73
73
  flet/controls/padding.py,sha256=TjTudMD8FkHeOJnSX7v5nUHtcq9GNS12wY65wcW-EF0,1757
74
- flet/controls/page.py,sha256=uvnnOLvLZwE78OhXWfLb-G3biyOqdrVYWnE_s8p-310,49287
74
+ flet/controls/page.py,sha256=npjomQb0ddNZZmcbS2x2Q5kl_5A2U0I1QPhafdMYS0Y,51378
75
75
  flet/controls/painting.py,sha256=urn3dNX_Sta9SMjIIxQJAQAF-qFS1MnundRaVCKNOAs,13975
76
76
  flet/controls/query_string.py,sha256=ZosheRtnbEaATPZIM9_UvsfyezK5rA8p7n0h663BGZ8,3301
77
77
  flet/controls/ref.py,sha256=FUN7XdvSHlQwLAg6so9EJjy0ZJ0zVP8eTf263hTRvU8,813
@@ -229,7 +229,7 @@ flet/controls/services/battery.py,sha256=KtdWlHOBNIK8sA6gzQHG76p8_DXKnodv-lqrXTF
229
229
  flet/controls/services/browser_context_menu.py,sha256=xaQjEiZOxVS-fZ_8Q-fNgNyUnKgHZlTBO0-Jr_kKEcw,1708
230
230
  flet/controls/services/clipboard.py,sha256=O5U6BB2GfNaL4qx_ZestLcyK4OvCC_44ZDUIgxC-CyM,4269
231
231
  flet/controls/services/connectivity.py,sha256=iFX2PELhwdmg_zcwPQGXLjtEzRiYoM0Fii9rSbzt5fg,1555
232
- flet/controls/services/file_picker.py,sha256=lG9Lajzyoy6CKl-KyNK9d9uOFgXt9aAhrTjXRpMVHmM,15322
232
+ flet/controls/services/file_picker.py,sha256=_32ssSbSh41sBCR-diHRgnVExVzu3ea4OF-gZj4q2qk,15340
233
233
  flet/controls/services/gyroscope.py,sha256=5qjDU48hp-kK8l9sFA8TQMbue96w8NV_caVTsxHe-0c,2345
234
234
  flet/controls/services/haptic_feedback.py,sha256=VU0Fb0OfXmqlj3zBnUZ8jNpkRfPKMq8I4mCjl9BnhcU,1417
235
235
  flet/controls/services/magnetometer.py,sha256=bK4DFGwfwGxXYOVFJINrEQG9p-ikA234dvaogdyWqok,2825
@@ -250,7 +250,7 @@ flet/messaging/flet_dart_bridge_server.py,sha256=kJcu5U4N6ia488FcYhBMu-RQptHWYc8
250
250
  flet/messaging/flet_socket_server.py,sha256=yizYjhsSgIc_vtZKvCoejHWd5-hTvjptPtI8jf-DbdM,19789
251
251
  flet/messaging/protocol.py,sha256=mo1kouwjQFznt7EDWzwIof1b3H8JuJ7KiD6mOvLHAYM,15830
252
252
  flet/messaging/pyodide_connection.py,sha256=l2ZFGnm8elx1YxrhhkNFj_AvxINcUyQRhKn5BuFVn-w,8844
253
- flet/messaging/session.py,sha256=i2nvEygFg6NRVhcZDzSA9XvQMZedgA2X4tQ_35s4aMo,27499
253
+ flet/messaging/session.py,sha256=8G9vFVjgUmjDZc8rRYNc9oeakAfTqD90FYDubg4JZ9k,32075
254
254
  flet/messaging/session_store.py,sha256=xvKjWmeB_m_cSv0q6M3c91p7xYrBcKdeLRDIHnmUsVY,1758
255
255
  flet/pubsub/__init__.py,sha256=qWcHYUa7oQEKysceGCeYG2AgIe0IO18NRXiP47jb_6o,126
256
256
  flet/pubsub/pubsub_client.py,sha256=8cu576tbuuh7xgD1iIiUvKfABkTbVHFsY4b17XKsaXk,3021
@@ -281,10 +281,10 @@ flet/utils/platform_utils.py,sha256=yNFW2yC4HajI8KDFFuxdg0XbaRzXcue623WXBb7oclc,
281
281
  flet/utils/slugify.py,sha256=SJMNUMcwuAUbHDDmggPz7Dvk7H4BiiPV-oR0xtEbYJk,468
282
282
  flet/utils/strings.py,sha256=LJBd9R7GvhCyvOCUA3SId_nwMsiXeDNe49Su5BaT2No,388
283
283
  flet/utils/typing_utils.py,sha256=asp2wpBNNWH8kSxAzI2hvnpyKIgwXqGen27VmKcTUt0,989
284
- flet/utils/validation.py,sha256=ZOGIANcVIZTcYMUPiyTUDXJCNF9eBUosZj6ZExvs_78,60899
284
+ flet/utils/validation.py,sha256=qdO9EcebAu1cGv8QVR1AsDdtQn16xVFtcwjn0599Hng,60933
285
285
  flet/utils/vector.py,sha256=nKDWoA-WhdRsg0kKn2b4kKeDkSLxWAhdVnXjPPwzMXI,5163
286
- flet-1.1.0.dev0.dist-info/METADATA,sha256=hMxcpTkvZ-rhzYMaQPsD1DytduEho16soG33D4dWQLk,7579
287
- flet-1.1.0.dev0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
288
- flet-1.1.0.dev0.dist-info/entry_points.txt,sha256=BcV9ss1uxSZLYpcRblgEcbSP6ib7zCi_PUQCmfUG7rA,77
289
- flet-1.1.0.dev0.dist-info/top_level.txt,sha256=HbLrSnWJX2jZOEZAI14cGzW8Q5BbOGTtE-7knD5FDh0,5
290
- flet-1.1.0.dev0.dist-info/RECORD,,
286
+ flet-1.1.0.dev2.dist-info/METADATA,sha256=jKw9fxrHILYTLhgJN6TGd7nPni66lVXx-rq9caK-_yo,7579
287
+ flet-1.1.0.dev2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
288
+ flet-1.1.0.dev2.dist-info/entry_points.txt,sha256=BcV9ss1uxSZLYpcRblgEcbSP6ib7zCi_PUQCmfUG7rA,77
289
+ flet-1.1.0.dev2.dist-info/top_level.txt,sha256=HbLrSnWJX2jZOEZAI14cGzW8Q5BbOGTtE-7knD5FDh0,5
290
+ flet-1.1.0.dev2.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5