| 1 |
# Copyright 2014 Open Source Robotics Foundation, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
import os |
| 16 |
import threading |
| 17 |
import warnings |
| 18 |
|
| 19 |
_thread_local = threading.local() |
| 20 |
|
| 21 |
|
| 22 |
def get_loop_impl(asyncio): |
| 23 |
# See the note in |
| 24 |
# https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop # noqa |
| 25 |
# In short, between Python 3.10.0 and 3.10.8, this unconditionally raises a |
| 26 |
# DeprecationWarning. But after 3.10.8, it only raises the warning if |
| 27 |
# ther eis no current loop set in the policy. Since we are setting a loop |
| 28 |
# in the policy, this warning is spurious, and will go away once we get |
| 29 |
# away from Python 3.10.6 (verified with Python 3.11.3). |
| 30 |
with warnings.catch_warnings(): |
| 31 |
warnings.filterwarnings( |
| 32 |
'ignore', |
| 33 |
'There is no current event loop', |
| 34 |
DeprecationWarning) |
| 35 |
|
| 36 |
global _thread_local |
| 37 |
if getattr(_thread_local, 'loop_has_been_setup', False): |
| 38 |
return asyncio.get_event_loop() |
| 39 |
# Setup this thread's loop and return it |
| 40 |
if os.name == 'nt': |
| 41 |
try: |
| 42 |
loop = asyncio.get_event_loop() |
| 43 |
if not isinstance(loop, asyncio.ProactorEventLoop): |
| 44 |
# Before replacing the existing loop, explicitly |
| 45 |
# close it to prevent an implicit close during |
| 46 |
# garbage collection, which may or may not be a |
| 47 |
# problem depending on the loop implementation. |
| 48 |
loop.close() |
| 49 |
loop = asyncio.ProactorEventLoop() |
| 50 |
asyncio.set_event_loop(loop) |
| 51 |
except (RuntimeError, AssertionError): |
| 52 |
loop = asyncio.ProactorEventLoop() |
| 53 |
asyncio.set_event_loop(loop) |
| 54 |
else: |
| 55 |
try: |
| 56 |
loop = asyncio.get_event_loop() |
| 57 |
except (RuntimeError, AssertionError): |
| 58 |
loop = asyncio.new_event_loop() |
| 59 |
asyncio.set_event_loop(loop) |
| 60 |
_thread_local.loop_has_been_setup = True |
| 61 |
|
| 62 |
return loop |