Answer the question
In order to leave comments, you need to log in
Should I pass loop to another thread?
The question is purely the nature of "what is the right way." Essence: There is a class in which I need to use telethon's TelegramClient. But I can’t initialize it in one thread and start it in another thread, because even if I supposedly use telethon.sync, it still receives a loop from itself and does everything asynchronously. It turns out that you need to either initialize it in __init__ and pass loop from the first thread to the second as a function argument, or initialize and start in one, second thread, but paycharm swears at this, supposedly everything needs to be initialized in __init__. 2 codes provided below.
import asyncio
from threading import Thread
from telethon import TelegramClient
class Binance:
def __init__(self):
self.loop = asyncio.get_event_loop()
self.tg_client = TelegramClient('sess', api_id, api_hash)
def updating(self, loop):
asyncio.set_event_loop(loop)
self.tg_client.start(phone, password)
print('logged in')
binance = Binance()
updater = Thread(target=binance.updating, args=[binance.loop])
updater.start()
input()
import asyncio
from threading import Thread
from telethon import TelegramClient
class Binance:
def __init__(self):
...
def updating(self):
asyncio.set_event_loop(asyncio.new_event_loop())
self.tg_client = TelegramClient('sess', api_id, api_hash) # вот здесь ругается пайчарм
self.tg_client.start(phone, password)
print('logged in')
binance = Binance()
updater = Thread(target=binance.updating)
updater.start()
input()
Answer the question
In order to leave comments, you need to log in
It's best to avoid thread sharing and async altogether. There are good reasons to combine them, it is better to strive to ensure that each thread has its own event loop, since it is not thread safe.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question