@@ -1402,6 +1402,8 @@ def run(x: object) -> object: ...
14021402
14031403[case testAsyncIntrospection]
14041404import inspect
1405+ import sys
1406+
14051407from functools import wraps
14061408from typing import Any, Callable, TypeVar, cast
14071409
@@ -1450,19 +1452,30 @@ class T:
14501452 async def returns_two_async(self) -> int:
14511453 return 2
14521454
1455+ def is_coroutine(fn):
1456+ if sys.version_info >= (3, 10):
1457+ return inspect.iscoroutinefunction(fn)
1458+
1459+ # inspect on older python versions does not support function-like objects.
1460+ # Below is a simplified implementation of iscoroutinefunction.
1461+ if not hasattr(fn, "__code__"):
1462+ return False
1463+ CO_COROUTINE = 0x0080
1464+ return bool(fn.__code__.co_flags & CO_COROUTINE)
1465+
14531466def test_function() -> None:
1454- assert not inspect.iscoroutinefunction (identity)
1455- assert inspect.iscoroutinefunction (identity_async)
1467+ assert not is_coroutine (identity)
1468+ assert is_coroutine (identity_async)
14561469
1457- assert not inspect.iscoroutinefunction (wrapped)
1458- assert inspect.iscoroutinefunction (wrapped_async)
1470+ assert not is_coroutine (wrapped)
1471+ assert is_coroutine (wrapped_async)
14591472
14601473def test_method() -> None:
1461- assert not inspect.iscoroutinefunction (T.returns_one)
1462- assert inspect.iscoroutinefunction (T.returns_one_async)
1474+ assert not is_coroutine (T.returns_one)
1475+ assert is_coroutine (T.returns_one_async)
14631476
1464- assert not inspect.iscoroutinefunction (T.returns_two)
1465- assert inspect.iscoroutinefunction (T.returns_two_async)
1477+ assert not is_coroutine (T.returns_two)
1478+ assert is_coroutine (T.returns_two_async)
14661479
14671480def test_nested() -> None:
14681481 def nested() -> int:
@@ -1479,8 +1492,8 @@ def test_nested() -> None:
14791492 async def nested_wrapped_async() -> int:
14801493 return 2
14811494
1482- assert not inspect.iscoroutinefunction (nested)
1483- assert inspect.iscoroutinefunction (nested_async)
1495+ assert not is_coroutine (nested)
1496+ assert is_coroutine (nested_async)
14841497
1485- assert not inspect.iscoroutinefunction (nested_wrapped)
1486- assert inspect.iscoroutinefunction (nested_wrapped_async)
1498+ assert not is_coroutine (nested_wrapped)
1499+ assert is_coroutine (nested_wrapped_async)
0 commit comments