【问题标题】:Telethon asyncio type hintTelethon 异步类型提示
【发布时间】: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 类型的对象。
  • 我对@9​​87654332@一无所知,但大概它是围绕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


【解决方案1】:

TotalList 只是一个方便的类,可以帮助我返回带有.total 字段的列表。您可能只想添加这一行:

from telethon.tl.custom import Dialog

def filter_open_dialogs(dialogs, filter_list):
    dialog: Dialog
    ...  # rest of code in the method

这应该告诉 PyCharm 正确输入提示。我认为您不能指定自定义类的内部类型。

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2020-09-19
    • 2021-12-26
    • 2016-03-22
    • 2018-08-27
    • 2023-02-10
    • 2017-11-01
    • 2018-12-04
    • 2017-03-10
    相关资源
    最近更新 更多