Skip to content

Commit 3cb059d

Browse files
authored
Update __init__.py
1 parent 0d5b534 commit 3cb059d

1 file changed

Lines changed: 31 additions & 26 deletions

File tree

qasync/__init__.py

Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -830,30 +830,35 @@ def wrapper(*args, **kwargs):
830830

831831
return outer_decorator
832832

833-
@contextlib.contextmanager
834-
def _use_qeventloop(loop_factory):
835-
app = QApplication.instance() or QApplication([sys.argv])
836-
if loop_factory is None:
837-
loop = QEventLoop(app)
838-
else:
839-
loop = loop_factory(app)
840-
try:
841-
old_loop = asyncio.get_event_loop()
842-
except RuntimeError: # No current event loop
843-
old_loop = None
844-
asyncio.set_event_loop(loop)
845-
try:
846-
yield loop
847-
finally:
848-
loop.close()
849-
asyncio.set_event_loop(None)
850833

851-
# A run function matching the signature of asyncio.run
852-
def run(main_coro, *, debug=None, loop_factory=None):
853-
"""
854-
Run the given coroutine using a QEventLoop.
855-
"""
856-
with _use_qeventloop(loop_factory) as loop:
857-
if debug is not None:
858-
loop.set_debug(debug)
859-
return loop.run_until_complete(main_coro)
834+
if sys.version_info < (3, 14): # Backwards compatibility with the policy, since there are classes without _ to begin with.
835+
class QEventLoopPolicyMixin:
836+
def new_event_loop(self):
837+
return QEventLoop(QApplication.instance() or QApplication(sys.argv))
838+
839+
840+
class DefaultQEventLoopPolicy(
841+
QEventLoopPolicyMixin,
842+
asyncio.DefaultEventLoopPolicy,
843+
):
844+
pass
845+
846+
847+
@contextlib.contextmanager
848+
def _set_event_loop_policy(policy):
849+
old_policy = asyncio.get_event_loop_policy()
850+
asyncio.set_event_loop_policy(policy)
851+
try:
852+
yield
853+
finally:
854+
asyncio.set_event_loop_policy(old_policy)
855+
856+
857+
def run(*args, **kwargs):
858+
with _set_event_loop_policy(DefaultQEventLoopPolicy()):
859+
return asyncio.run(*args, **kwargs))
860+
861+
else:
862+
863+
def run(*args, **kwargs):
864+
return asyncio.run(*args, **kwargs, loop_factory=QEventLoop(QApplication.instance() or QApplication(sys.argv))

0 commit comments

Comments
 (0)