Skip to content

Commit cb15300

Browse files
authored
Lazy import asyncio.sleep as it's expensive (#450)
On my system, importing tenacity (_without tornado_) takes 35ms, and asyncio is singlehandedly responsible for 15ms. Some users do not ever use AsyncRetrying (or asyncio in their project generally) and it would be a shame for them to incur a unnecessary import penalty. Full disclaimer: I pursued this change primarily to reduce pip's startup time where asyncio was a nontrivial portion of the import timeline.
1 parent c5d2d8b commit cb15300

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

tenacity/_asyncio.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import functools
1919
import sys
2020
import typing as t
21-
from asyncio import sleep
2221

2322
from tenacity import AttemptManager
2423
from tenacity import BaseRetrying
@@ -31,11 +30,20 @@
3130
WrappedFn = t.TypeVar("WrappedFn", bound=t.Callable[..., t.Awaitable[t.Any]])
3231

3332

33+
def asyncio_sleep(duration: float) -> t.Awaitable[None]:
34+
# Lazy import asyncio as it's expensive (responsible for 25-50% of total import overhead).
35+
import asyncio
36+
37+
return asyncio.sleep(duration)
38+
39+
3440
class AsyncRetrying(BaseRetrying):
3541
sleep: t.Callable[[float], t.Awaitable[t.Any]]
3642

3743
def __init__(
38-
self, sleep: t.Callable[[float], t.Awaitable[t.Any]] = sleep, **kwargs: t.Any
44+
self,
45+
sleep: t.Callable[[float], t.Awaitable[t.Any]] = asyncio_sleep,
46+
**kwargs: t.Any,
3947
) -> None:
4048
super().__init__(**kwargs)
4149
self.sleep = sleep

0 commit comments

Comments
 (0)