File: 0001-py314-avoid-asyncio-get_event_loop.patch

package info (click to toggle)
python-rx 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,204 kB
  • sloc: python: 39,525; javascript: 77; makefile: 24
file content (384 lines) | stat: -rw-r--r-- 14,860 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
From: Steve Traylen <steve.traylen@cern.ch>
Date: Sun, 9 Mar 2025 00:30:43 +0100
Subject: Avoid use of asyncio.get_event_loop (3.14)

Python 3.14 will remove "asyncio.get_event_loop"

https://docs.python.org/dev/whatsnew/3.14.html#id6

Replace "asyncio.get_event_loop"

Origin: upstream, https://github.com/ReactiveX/RxPY/pull/728
Bug-Debian: https://bugs.debian.org/1123306
Last-Update: 2025-12-31
---
 reactivex/observable/observable.py                 |  6 +++-
 reactivex/operators/_tofuture.py                   | 33 ++++++++++++++--------
 reactivex/scheduler/eventloop/asyncioscheduler.py  |  2 +-
 .../eventloop/asynciothreadsafescheduler.py        | 12 ++++----
 tests/test_observable/test_flatmap_async.py        |  2 +-
 tests/test_observable/test_fromfuture.py           |  8 +++---
 tests/test_observable/test_start.py                |  4 +--
 tests/test_observable/test_tofuture.py             | 14 ++++-----
 .../test_eventloop/test_asyncioscheduler.py        | 10 +++----
 .../test_asynciothreadsafescheduler.py             | 10 +++----
 10 files changed, 56 insertions(+), 45 deletions(-)

diff --git a/reactivex/observable/observable.py b/reactivex/observable/observable.py
index 6e864da..5ca2373 100644
--- a/reactivex/observable/observable.py
+++ b/reactivex/observable/observable.py
@@ -259,7 +259,11 @@ class Observable(abc.ObservableBase[_T_out]):
         """
         from ..operators._tofuture import to_future_
 
-        loop = asyncio.get_event_loop()
+        try:
+            loop = asyncio.get_running_loop()
+        except RuntimeError:
+            loop = asyncio.new_event_loop()
+
         future: asyncio.Future[_T_out] = self.pipe(
             to_future_(scheduler=AsyncIOScheduler(loop=loop))
         )
diff --git a/reactivex/operators/_tofuture.py b/reactivex/operators/_tofuture.py
index 8369aba..a7b2606 100644
--- a/reactivex/operators/_tofuture.py
+++ b/reactivex/operators/_tofuture.py
@@ -9,15 +9,11 @@ _T = TypeVar("_T")
 
 
 def to_future_(
-    future_ctor: Optional[Callable[[], "Future[_T]"]] = None,
+    future_ctor: Optional[Callable[[], Future[_T]]] = None,
     scheduler: Optional[abc.SchedulerBase] = None,
-) -> Callable[[Observable[_T]], "Future[_T]"]:
-    future_ctor_: Callable[[], "Future[_T]"] = (
-        future_ctor or asyncio.get_event_loop().create_future
-    )
-    future: "Future[_T]" = future_ctor_()
+) -> Callable[[Observable[_T]], Future[_T]]:
 
-    def to_future(source: Observable[_T]) -> "Future[_T]":
+    def to_future(source: Observable[_T]) -> Future[_T]:
         """Converts an existing observable sequence to a Future.
 
         If the observable emits a single item, then this item is set as the
@@ -33,25 +29,38 @@ def to_future_(
         Returns:
             A future with the last value from the observable sequence.
         """
+        if future_ctor is not None:
+            future_ctor_ = future_ctor
+        else:
+            try:
+                future_ctor_ = asyncio.get_running_loop().create_future
+            except RuntimeError:
+
+                def create_future() -> Future[_T]:
+                    return Future()  # Explicitly using Future[_T]
+
+                future_ctor_ = create_future  # If no running loop
+
+        future: Future[_T] = future_ctor_()
 
         has_value = False
-        last_value = cast(_T, None)
+        last_value: Optional[_T] = None
 
-        def on_next(value: _T):
+        def on_next(value: _T) -> None:
             nonlocal last_value
             nonlocal has_value
             last_value = value
             has_value = True
 
-        def on_error(err: Exception):
+        def on_error(err: Exception) -> None:
             if not future.cancelled():
                 future.set_exception(err)
 
-        def on_completed():
+        def on_completed() -> None:
             nonlocal last_value
             if not future.cancelled():
                 if has_value:
-                    future.set_result(last_value)
+                    future.set_result(cast(_T, last_value))
                 else:
                     future.set_exception(SequenceContainsNoElementsError())
             last_value = None
diff --git a/reactivex/scheduler/eventloop/asyncioscheduler.py b/reactivex/scheduler/eventloop/asyncioscheduler.py
index 16d9f64..e7b5043 100644
--- a/reactivex/scheduler/eventloop/asyncioscheduler.py
+++ b/reactivex/scheduler/eventloop/asyncioscheduler.py
@@ -26,7 +26,7 @@ class AsyncIOScheduler(PeriodicScheduler):
 
         Args:
             loop: Instance of asyncio event loop to use; typically, you would
-                get this by asyncio.get_event_loop()
+                get this by asyncio.get_running_loop()
         """
         super().__init__()
         self._loop: asyncio.AbstractEventLoop = loop
diff --git a/reactivex/scheduler/eventloop/asynciothreadsafescheduler.py b/reactivex/scheduler/eventloop/asynciothreadsafescheduler.py
index 9287419..7c792a6 100644
--- a/reactivex/scheduler/eventloop/asynciothreadsafescheduler.py
+++ b/reactivex/scheduler/eventloop/asynciothreadsafescheduler.py
@@ -145,13 +145,11 @@ class AsyncIOThreadSafeScheduler(AsyncIOScheduler):
         """
         if not self._loop.is_running():
             return True
-        current_loop = None
+
         try:
-            # In python 3.7 there asyncio.get_running_loop() is prefered.
-            current_loop = asyncio.get_event_loop()
+            current_loop = asyncio.get_running_loop()
         except RuntimeError:
-            # If there is no loop in current thread at all, and it is not main
-            # thread, we get error like:
-            # RuntimeError: There is no current event loop in thread 'Thread-1'
-            pass
+            # If no running event loop is found, assume we're in a different thread
+            return True
+
         return self._loop == current_loop
diff --git a/tests/test_observable/test_flatmap_async.py b/tests/test_observable/test_flatmap_async.py
index 6907c29..c012b7f 100644
--- a/tests/test_observable/test_flatmap_async.py
+++ b/tests/test_observable/test_flatmap_async.py
@@ -9,7 +9,7 @@ from reactivex.subject import Subject
 class TestFlatMapAsync(unittest.TestCase):
     def test_flat_map_async(self):
         actual_next = None
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         scheduler = AsyncIOScheduler(loop=loop)
 
         def mapper(i: int):
diff --git a/tests/test_observable/test_fromfuture.py b/tests/test_observable/test_fromfuture.py
index 7f85d80..833e284 100644
--- a/tests/test_observable/test_fromfuture.py
+++ b/tests/test_observable/test_fromfuture.py
@@ -7,7 +7,7 @@ import reactivex
 
 class TestFromFuture(unittest.TestCase):
     def test_future_success(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         success = [False, True, False]
 
         async def go():
@@ -31,7 +31,7 @@ class TestFromFuture(unittest.TestCase):
         assert all(success)
 
     def test_future_failure(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         success = [True, False, True]
 
         async def go():
@@ -57,7 +57,7 @@ class TestFromFuture(unittest.TestCase):
         assert all(success)
 
     def test_future_cancel(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         success = [True, False, True]
 
         async def go():
@@ -80,7 +80,7 @@ class TestFromFuture(unittest.TestCase):
         assert all(success)
 
     def test_future_dispose(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         success = [True, True, True]
 
         async def go():
diff --git a/tests/test_observable/test_start.py b/tests/test_observable/test_start.py
index 5c6bb4a..9694c93 100644
--- a/tests/test_observable/test_start.py
+++ b/tests/test_observable/test_start.py
@@ -16,7 +16,7 @@ created = ReactiveTest.created
 
 class TestStart(unittest.TestCase):
     def test_start_async(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         success = [False]
 
         async def go():
@@ -36,7 +36,7 @@ class TestStart(unittest.TestCase):
         assert all(success)
 
     def test_start_async_error(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         success = [False]
 
         async def go():
diff --git a/tests/test_observable/test_tofuture.py b/tests/test_observable/test_tofuture.py
index e956974..e5a27fd 100644
--- a/tests/test_observable/test_tofuture.py
+++ b/tests/test_observable/test_tofuture.py
@@ -18,7 +18,7 @@ created = ReactiveTest.created
 
 class TestToFuture(unittest.TestCase):
     def test_await_success(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         result = None
 
         async def go():
@@ -30,7 +30,7 @@ class TestToFuture(unittest.TestCase):
         assert result == 42
 
     def test_await_success_on_sequence(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         result = None
 
         async def go():
@@ -42,7 +42,7 @@ class TestToFuture(unittest.TestCase):
         assert result == 42
 
     def test_await_error(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         error = Exception("error")
         result = None
 
@@ -58,7 +58,7 @@ class TestToFuture(unittest.TestCase):
         assert result == error
 
     def test_await_empty_observable(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         result = None
 
         async def go():
@@ -71,7 +71,7 @@ class TestToFuture(unittest.TestCase):
         )
 
     def test_await_with_delay(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         result = None
 
         async def go():
@@ -83,7 +83,7 @@ class TestToFuture(unittest.TestCase):
         assert result == 42
 
     def test_cancel(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
 
         async def go():
             source = reactivex.return_value(42)
@@ -96,7 +96,7 @@ class TestToFuture(unittest.TestCase):
         self.assertRaises(asyncio.CancelledError, loop.run_until_complete, go())
 
     def test_dispose_on_cancel(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         sub = Subject()
 
         async def using_sub():
diff --git a/tests/test_scheduler/test_eventloop/test_asyncioscheduler.py b/tests/test_scheduler/test_eventloop/test_asyncioscheduler.py
index e6a9622..e637d3e 100644
--- a/tests/test_scheduler/test_eventloop/test_asyncioscheduler.py
+++ b/tests/test_scheduler/test_eventloop/test_asyncioscheduler.py
@@ -13,14 +13,14 @@ CI = os.getenv("CI") is not None
 class TestAsyncIOScheduler(unittest.TestCase):
     @pytest.mark.skipif(CI, reason="Flaky test in GitHub Actions")
     def test_asyncio_schedule_now(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         scheduler = AsyncIOScheduler(loop)
         diff = scheduler.now - datetime.fromtimestamp(loop.time(), tz=timezone.utc)
         assert abs(diff) < timedelta(milliseconds=2)  # NOTE: may take 1 ms in CI
 
     @pytest.mark.skipif(CI, reason="Test is flaky in GitHub Actions")
     def test_asyncio_schedule_now_units(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         scheduler = AsyncIOScheduler(loop)
         diff = scheduler.now
         yield from asyncio.sleep(0.1)
@@ -28,7 +28,7 @@ class TestAsyncIOScheduler(unittest.TestCase):
         assert timedelta(milliseconds=80) < diff < timedelta(milliseconds=180)
 
     def test_asyncio_schedule_action(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
 
         async def go():
             scheduler = AsyncIOScheduler(loop)
@@ -46,7 +46,7 @@ class TestAsyncIOScheduler(unittest.TestCase):
         loop.run_until_complete(go())
 
     def test_asyncio_schedule_action_due(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
 
         async def go():
             scheduler = AsyncIOScheduler(loop)
@@ -67,7 +67,7 @@ class TestAsyncIOScheduler(unittest.TestCase):
         loop.run_until_complete(go())
 
     def test_asyncio_schedule_action_cancel(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
 
         async def go():
             ran = False
diff --git a/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py b/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py
index 12f75ac..2c19df1 100644
--- a/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py
+++ b/tests/test_scheduler/test_eventloop/test_asynciothreadsafescheduler.py
@@ -14,14 +14,14 @@ CI = os.getenv("CI") is not None
 class TestAsyncIOThreadSafeScheduler(unittest.TestCase):
     @pytest.mark.skipif(CI, reason="Flaky test in GitHub Actions")
     def test_asyncio_threadsafe_schedule_now(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         scheduler = AsyncIOThreadSafeScheduler(loop)
         diff = scheduler.now - datetime.fromtimestamp(loop.time(), tz=timezone.utc)
         assert abs(diff) < timedelta(milliseconds=2)
 
     @pytest.mark.skipif(CI, reason="Flaky test in GitHub Actions")
     def test_asyncio_threadsafe_schedule_now_units(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
         scheduler = AsyncIOThreadSafeScheduler(loop)
         diff = scheduler.now
         yield from asyncio.sleep(0.1)
@@ -29,7 +29,7 @@ class TestAsyncIOThreadSafeScheduler(unittest.TestCase):
         assert timedelta(milliseconds=80) < diff < timedelta(milliseconds=180)
 
     def test_asyncio_threadsafe_schedule_action(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
 
         async def go():
             scheduler = AsyncIOThreadSafeScheduler(loop)
@@ -50,7 +50,7 @@ class TestAsyncIOThreadSafeScheduler(unittest.TestCase):
         loop.run_until_complete(go())
 
     def test_asyncio_threadsafe_schedule_action_due(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
 
         async def go():
             scheduler = AsyncIOThreadSafeScheduler(loop)
@@ -74,7 +74,7 @@ class TestAsyncIOThreadSafeScheduler(unittest.TestCase):
         loop.run_until_complete(go())
 
     def test_asyncio_threadsafe_schedule_action_cancel(self):
-        loop = asyncio.get_event_loop()
+        loop = asyncio.new_event_loop()
 
         async def go():
             ran = False