英文:
How to correctly implement type `AList` for custom class `alist`, similiar to `List` and `list`
问题
以下是您要翻译的内容:
"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."
英文:
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.
答案1
得分: 2
list
本身是泛型的(自Python 3.9起);只需使用
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
已弃用,这是在无法通用使用内置类型的时代的遗物。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论