How can I achieve the same with custom class alist
and its type alias AList
as how builtin list
and List
from typing
work?
I can see that type List
is defined following way in typing
:
List = _alias(list, 1, inst=False, name='List')
_alias
is alias for internal class _SpecialGenericAlias
and AFAIK those should not be used externally.
I have now following code:
import asyncio
from typing import Generic, TypeVar
T = TypeVar("T")
class alist(list, Generic[T]): # pylint: disable=invalid-name
async def __aiter__(self):
for _ in self:
yield _
AList = alist[T]
async def func(integers: AList[int]):
async for integer in integers:
print(integer)
asyncio.run(func(alist([1, 2, 3])))
Using VSCode and when hovering mouse on integer
on line async for integer in integers:
it shows "(variable) integer: Unknown". It leads me wonder if this will make auto completion tools and type checkers understand AList
and alist
correctly. Code runs without errors.
list
itself is generic (since Python 3.9); just use
import asyncio
from typing import Generic, TypeVar
T = TypeVar("T")
class alist(list[T]):
async def __aiter__(self):
for _ in self:
yield _
async def func(integers: alist[int]):
async for integer in integers:
print(integer)
asyncio.run(func(alist([1, 2, 3])))
typing.List
is deprecated, an artifact of a time when the built-in types could not be used generically.