Skip to content

Commit e0ce07c

Browse files
committed
Use native async/await in coroutine wrappers and test Python 3.12-3.14 in CI (Closes #403, Closes #409)
1 parent fdf104d commit e0ce07c

3 files changed

Lines changed: 18 additions & 9 deletions

File tree

‎.github/workflows/lint_python.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ jobs:
5959
- major_dot_minor: '3.9'
6060
- major_dot_minor: '3.10'
6161
- major_dot_minor: '3.11'
62+
- major_dot_minor: '3.12'
63+
- major_dot_minor: '3.13'
64+
- major_dot_minor: '3.14'
6265
steps:
6366
- uses: actions/checkout@v4
6467
- uses: actions/setup-python@v5

‎memory_profiler.py‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,9 @@
77

88
_CMD_USAGE = "python -m memory_profiler script_file.py"
99

10-
from asyncio import iscoroutinefunction
1110
from contextlib import contextmanager
1211
from functools import partial, wraps
13-
from types import coroutine
12+
from inspect import iscoroutinefunction
1413
import builtins
1514
import inspect
1615
import linecache
@@ -756,11 +755,12 @@ def wrap_function(self, func):
756755
"""
757756

758757
if iscoroutinefunction(func):
759-
@coroutine
760-
def f(*args, **kwargs):
758+
# Use native `async def` / `await` rather than the legacy
759+
# `@types.coroutine` generator wrapper, which is rejected by
760+
# `asyncio.create_task()` in Python 3.12+.
761+
async def f(*args, **kwargs):
761762
with self._count_ctxmgr():
762-
res = yield from func(*args, **kwargs)
763-
return res
763+
return await func(*args, **kwargs)
764764
else:
765765
def f(*args, **kwds):
766766
with self._count_ctxmgr():
@@ -1156,10 +1156,9 @@ def profile(func=None, stream=None, precision=1, backend='psutil'):
11561156
)
11571157
if iscoroutinefunction(func):
11581158
@wraps(wrapped=func)
1159-
@coroutine
1160-
def wrapper(*args, **kwargs):
1159+
async def wrapper(*args, **kwargs):
11611160
prof = get_prof()
1162-
val = yield from prof(func)(*args, **kwargs)
1161+
val = await prof(func)(*args, **kwargs)
11631162
show_results_bound(prof)
11641163
return val
11651164
else:

‎test/test_async.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import inspect
23
import sys
34

45
from memory_profiler import profile
@@ -10,10 +11,16 @@ async def my_func():
1011
b = [2] * (2 * 10 ** 7)
1112
await asyncio.sleep(1e-2)
1213
del b
14+
return len(a)
15+
1316

1417
async def main():
18+
# Ensure @profile preserves the coroutine nature of async functions so
19+
# asyncio.create_task() accepts them on Python 3.12+.
20+
assert inspect.iscoroutinefunction(my_func)
1521
task = asyncio.create_task(my_func())
1622
res = await asyncio.gather(task)
23+
assert res == [10 ** 6]
1724

1825
async def main_legacy():
1926
future = asyncio.ensure_future(my_func())

0 commit comments

Comments
 (0)