Search code examples
pythontelegramtelethon

Is this valid usage of 'with' for TelegramClient and start()?


I want to use the context manager with and to pass the password to the start() at the same time. I think this can be done because in the documentation of the start() function it is written:

"""
Returns
   This `TelegramClient`, so initialization
   can be chained with ``.start()``."""

This code works as expected, but I dont find similar usage of with and start() in the telethon examples from documentation.

from telethon.sync import TelegramClient

api_id = 1111111111
api_hash = 1111111111
password = 1111111111

session = 'my_session'
client = TelegramClient(session, api_id, api_hash,
                        system_version="4.16.30-vxCUSTOM")

with client.start(password=password):
    client.run_until_disconnected()

Solution

  • Yes, the documentation simply states that client.start returns client (for whatever instance of TelegramClient is bound to the name client).

    That means

    client.start()
    with client:
        ...
    

    means the same thing as

    with client.start():
        ...