【发布时间】:2019-02-06 19:56:32
【问题描述】:
我在 python 中使用 telethon 库。我正在尝试使用类型提示来使 PyCharm 自动完成功能正常工作。在下面的代码 sn-p 中,函数 filter_open_dialogs 将函数 get_dialogs() 的返回值作为输入。阅读 Telethon 文档,我发现 get_dialogs() 的返回类型为 TotalList,因此将类型提示添加到 dialogs 输入参数。然后我尝试调用函数filter_open_dialogs:
from telethon.tl.types import User
from telethon.helpers import TotalList
from telethon import TelegramClient, sync
class Crawler:
def __init__(self, fetch: bool):
self._client = TelegramClient('some_name', my_api_id, 'my_secret_api_hash')
self._me = self._client.start(phone='my_phone_number', password='my_2fa_password')
if fetch:
self.get_open_dialogs()
def get_open_dialogs(self):
if self._me:
Crawler.filter_open_dialogs(self._me.get_dialogs(), [])
return self._me.get_dialogs()
@staticmethod
def filter_open_dialogs(dialogs: TotalList, filter_list: list):
result = []
if dialogs and dialogs.total:
for dialog in dialogs:
entity = dialog.entity
if not isinstance(entity, User) and entity.id not in filter_list:
result.append(entity)
return result
但在filter_open_dialogs(self._me.get_dialogs(), []) 行中,PyCharm 显示此警告:
预期类型 TotalList',改为“Coroutine”...
有没有想过怎么了?
【问题讨论】:
-
看起来
self._me.get_dialogs()没有返回TotalList类型的对象。 -
我对@987654332@一无所知,但大概它是围绕
asyncio或其他基于协程的库构建的,所以所有这些函数实际上都是你通常应该使用的协程await结果而不是直接使用它们?你能给我们一个minimal reproducible example吗? -
@JohnGordon 但在代码文档中它说:与
iter_dialogs相同,但返回aTotalList <telethon.helpers.TotalList> -
@abarnert 是的,这正是文档所说的,在新版本中他们使用的是
asyncio,但我对此一无所知。我将用一些代码更新帖子,以便能够重现问题。 -
@Offofue Changjng 一个从同步或线程或任何基于异步的大型库而不从根本上更改 API 的大型库似乎是一项艰巨的任务,所以如果某些文档我不会感到惊讶落后。如果该函数返回一个可等待对象,在等待时会为您提供
TotalList,但文档说它直接返回TotalList,这可能是您可以提交并且他们可以修复的文档错误。但同样,这只是对我不知道的图书馆的疯狂猜测,所以……希望其他人知道更多。 (但是:代码工作,如果你不尝试输入检查它吗?)
标签: python-3.x pycharm type-hinting telethon