Search code examples
pythonpycharmpython-typingtelethon

Telethon asyncio type hint


I'm using telethon library in python. I'm trying to use type hinting to get PyCharm auto-complete feature work right. In code snippet below, function filter_open_dialogs takes return value of function get_dialogs() as input. Reading telethon documentation, i found out that return type of get_dialogs() is TotalList so add type hint to dialogs input argument. Then i tried to call function 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

But in line filter_open_dialogs(self._me.get_dialogs(), []) , PyCharm shows this warning:

Expected type TotalList', got 'Coroutine' instead ...

Any thought what's going wrong?


Solution

  • TotalList is just a convenience class to help me return a list with a .total field. You probably just want to add this line:

    from telethon.tl.custom import Dialog
    
    def filter_open_dialogs(dialogs, filter_list):
        dialog: Dialog
        ...  # rest of code in the method
    

    That should tell PyCharm to type hint correctly. I don't think you can specify the inner type of a custom class.