Skip to content

Commit

Permalink
Move current_task import choice to module definition time
Browse files Browse the repository at this point in the history
Saves 1 hasattr call per usage of asgiref.timeout.current_task, and the same on Local.__getattr__/__setattr__ (which depends indirectly on SyncToAsync.get_current_task)

Note that the module level variable used in the timeout module has to be aliased to another name, because `current_task` is already in use by the public function name.
  • Loading branch information
kezabelle committed Aug 28, 2021
1 parent dfe87b2 commit c758984
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 9 deletions.
2 changes: 2 additions & 0 deletions asgiref/compatibility.py
Expand Up @@ -53,9 +53,11 @@ def guarantee_single_callable(application):
get_running_loop = asyncio.get_running_loop
run_future = asyncio.run
create_task = asyncio.create_task
current_task = asyncio.current_task
else:
# marked as deprecated in 3.10, did not exist before 3.7
get_running_loop = asyncio.get_event_loop
run_future = asyncio.ensure_future
# does nothing, this is fine for <3.7
create_task = lambda task: task
current_task = asyncio.Task.current_task
5 changes: 1 addition & 4 deletions asgiref/sync.py
Expand Up @@ -9,17 +9,14 @@
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Any, Callable, Dict, Optional, overload

from .compatibility import get_running_loop
from .compatibility import current_task, get_running_loop
from .current_thread_executor import CurrentThreadExecutor
from .local import Local

if sys.version_info >= (3, 7):
import contextvars

current_task = asyncio.current_task
else:
contextvars = None
current_task = asyncio.Task.current_task


def _restore_context(context):
Expand Down
8 changes: 3 additions & 5 deletions asgiref/timeout.py
Expand Up @@ -7,10 +7,11 @@


import asyncio
import sys
from types import TracebackType
from typing import Any, Optional, Type

from .compatibility import current_task as asyncio_current_task


class timeout:
"""timeout context manager.
Expand Down Expand Up @@ -114,10 +115,7 @@ def _cancel_task(self) -> None:


def current_task(loop: asyncio.AbstractEventLoop) -> "Optional[asyncio.Task[Any]]":
if sys.version_info >= (3, 7):
task = asyncio.current_task(loop=loop)
else:
task = asyncio.Task.current_task(loop=loop)
task = asyncio_current_task(loop=loop)
if task is None:
# this should be removed, tokio must use register_task and family API
fn = getattr(loop, "current_task", None)
Expand Down

0 comments on commit c758984

Please sign in to comment.