Skip to content

Commit

Permalink
Reformat with code formatter
Browse files Browse the repository at this point in the history
`ruff format` with ruff 0.5.7
  • Loading branch information
mattsta committed Aug 15, 2024
1 parent 6fd4dfd commit 7b96134
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 35 deletions.
56 changes: 33 additions & 23 deletions nest_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,20 @@ def _get_event_loop(stacklevel=3):
return loop

# Use module level _current_tasks, all_tasks and patch run method.
if hasattr(asyncio, '_nest_patched'):
if hasattr(asyncio, "_nest_patched"):
return
if sys.version_info >= (3, 6, 0):
asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \
asyncio.tasks._PyTask
asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = \
asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = asyncio.tasks._PyTask
asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = (
asyncio.futures._PyFuture
)
if sys.version_info < (3, 7, 0):
asyncio.tasks._current_tasks = asyncio.tasks.Task._current_tasks
asyncio.all_tasks = asyncio.tasks.Task.all_tasks
if sys.version_info >= (3, 9, 0):
events._get_event_loop = events.get_event_loop = \
asyncio.get_event_loop = _get_event_loop
events._get_event_loop = events.get_event_loop = asyncio.get_event_loop = (
_get_event_loop
)
asyncio.run = run
asyncio._nest_patched = True

Expand Down Expand Up @@ -93,8 +94,7 @@ def run_until_complete(self, future):
if self._stopping:
break
if not f.done():
raise RuntimeError(
'Event loop stopped before Future completed.')
raise RuntimeError("Event loop stopped before Future completed.")
return f.result()

def _run_once(self):
Expand All @@ -108,10 +108,12 @@ def _run_once(self):
heappop(scheduled)

timeout = (
0 if ready or self._stopping
else min(max(
scheduled[0]._when - self.time(), 0), 86400) if scheduled
else None)
0
if ready or self._stopping
else min(max(scheduled[0]._when - self.time(), 0), 86400)
if scheduled
else None
)
event_list = self._selector.select(timeout)
self._process_events(event_list)

Expand Down Expand Up @@ -157,8 +159,10 @@ def manage_run(self):
events._set_running_loop(old_running_loop)
self._num_runs_pending -= 1
if self._is_proactorloop:
if (self._num_runs_pending == 0
and self._self_reading_future is not None):
if (
self._num_runs_pending == 0
and self._self_reading_future is not None
):
ov = self._self_reading_future._ov
self._self_reading_future.cancel()
if ov is not None:
Expand All @@ -167,7 +171,7 @@ def manage_run(self):

@contextmanager
def manage_asyncgens(self):
if not hasattr(sys, 'get_asyncgen_hooks'):
if not hasattr(sys, "get_asyncgen_hooks"):
# Python version is too old.
return
old_agen_hooks = sys.get_asyncgen_hooks()
Expand All @@ -176,7 +180,8 @@ def manage_asyncgens(self):
if self._asyncgens is not None:
sys.set_asyncgen_hooks(
firstiter=self._asyncgen_firstiter_hook,
finalizer=self._asyncgen_finalizer_hook)
finalizer=self._asyncgen_finalizer_hook,
)
yield
finally:
self._set_coroutine_origin_tracking(False)
Expand All @@ -187,23 +192,27 @@ def _check_running(self):
"""Do not throw exception if loop is already running."""
pass

if hasattr(loop, '_nest_patched'):
if hasattr(loop, "_nest_patched"):
return
if not isinstance(loop, asyncio.BaseEventLoop):
raise ValueError('Can\'t patch loop of type %s' % type(loop))
raise ValueError("Can't patch loop of type %s" % type(loop))
cls = loop.__class__
cls.run_forever = run_forever
cls.run_until_complete = run_until_complete
cls._run_once = _run_once
cls._check_running = _check_running
cls._check_runnung = _check_running # typo in Python 3.7 source
cls._num_runs_pending = 1 if loop.is_running() else 0
cls._is_proactorloop = (
os.name == 'nt' and issubclass(cls, asyncio.ProactorEventLoop))
cls._is_proactorloop = os.name == "nt" and issubclass(
cls, asyncio.ProactorEventLoop
)
if sys.version_info < (3, 7, 0):
cls._set_coroutine_origin_tracking = cls._set_coroutine_wrapper
curr_tasks = asyncio.tasks._current_tasks \
if sys.version_info >= (3, 7, 0) else asyncio.Task._current_tasks
curr_tasks = (
asyncio.tasks._current_tasks
if sys.version_info >= (3, 7, 0)
else asyncio.Task._current_tasks
)
cls._nest_patched = True


Expand All @@ -212,8 +221,9 @@ def _patch_tornado():
If tornado is imported before nest_asyncio, make tornado aware of
the pure-Python asyncio Future.
"""
if 'tornado' in sys.modules:
if "tornado" in sys.modules:
import tornado.concurrent as tc # type: ignore

tc.Future = asyncio.Future
if asyncio.Future not in tc.FUTURES:
tc.FUTURES += (asyncio.Future,)
20 changes: 8 additions & 12 deletions tests/nest_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


def exception_handler(loop, context):
print('Exception:', context)
print("Exception:", context)


class NestTest(unittest.TestCase):
Expand All @@ -27,7 +27,6 @@ async def coro(self):
return 42

def test_nesting(self):

async def f1():
result = self.loop.run_until_complete(self.coro())
self.assertEqual(result, await self.coro())
Expand All @@ -42,7 +41,6 @@ async def f2():
self.assertEqual(result, 42)

def test_ensure_future_with_run_until_complete(self):

async def f():
task = asyncio.ensure_future(self.coro())
return self.loop.run_until_complete(task)
Expand All @@ -51,19 +49,18 @@ async def f():
self.assertEqual(result, 42)

def test_ensure_future_with_run_until_complete_with_wait(self):

async def f():
task = asyncio.ensure_future(self.coro())
done, pending = self.loop.run_until_complete(
asyncio.wait([task], return_when=asyncio.ALL_COMPLETED))
asyncio.wait([task], return_when=asyncio.ALL_COMPLETED)
)
task = done.pop()
return task.result()

result = self.loop.run_until_complete(f())
self.assertEqual(result, 42)

def test_timeout(self):

async def f1():
await asyncio.sleep(0.1)

Expand All @@ -74,7 +71,6 @@ async def f2():
self.loop.run_until_complete(f2())

def test_two_run_until_completes_in_one_outer_loop(self):

async def f1():
self.loop.run_until_complete(asyncio.sleep(0.02))
return 4
Expand All @@ -83,14 +79,14 @@ async def f2():
self.loop.run_until_complete(asyncio.sleep(0.01))
return 2

result = self.loop.run_until_complete(
asyncio.gather(f1(), f2()))
result = self.loop.run_until_complete(asyncio.gather(f1(), f2()))
self.assertEqual(result, [4, 2])

@unittest.skipIf(sys.version_info < (3, 7, 0), 'No contextvars module')
@unittest.skipIf(sys.version_info < (3, 7, 0), "No contextvars module")
def test_contextvars(self):
from contextvars import ContextVar
var = ContextVar('var')

var = ContextVar("var")
var.set(0)

async def set_val():
Expand All @@ -105,5 +101,5 @@ async def coro():
self.assertEqual(result, 42)


if __name__ == '__main__':
if __name__ == "__main__":
unittest.main()

0 comments on commit 7b96134

Please sign in to comment.