0

I have a Bot class in bot.py:

import events


class Bot:
    def __init__(self, token, v):
        self.token = token
        self.v = v
        self.events = events.Events(self)

And also the events.py file:

import bot


class NewMessageEvent:
    def __init__(self, bot: bot.Bot):
        self.bot = bot
        self.someVar = "someVar"
        self.someVar2 = "someVar2"
        self.sender_id = "some_id"
        self.event_id = "some_id2"
        self.handlers = []
    
    def subscribe(self, handler):
        self.handlers.append(handler)

    def execute(self):
        for func in self.handlers:
            func(self)
    

class Events:
    def __init__(self, bot: bot.Bot):
        self.MESSAGE_NEW = NewMessageEvent(bot)
        #self.SMTH_ANOTHER = SomeAnotherEvent(bot)

You need all this to use it later on like this:

import bot
import events

mybot = bot.Bot("token", "api version")

def send_pic(event: events.NewMessageEvent):
    requests.get("link", headers = {"token": event.bot.token, "reply_to": event.sender_id})

mybot.events.MESSAGE_NEW.subscribe(send_pic)

As you can see, I got a recursive import. The Bot class uses the Events class, and in the Events class I need to specify a type hint for the bot argument (bot.Bot)

Is there any way to avoid recursive importing?

  • 4
    Does this answer your question? [Python type hinting without cyclic imports](https://stackoverflow.com/questions/39740632/python-type-hinting-without-cyclic-imports) – etnguyen03 Nov 12 '22 at 17:01
  • 1
    Does this [answer](https://stackoverflow.com/a/67673741/4834) help at all? – quamrana Nov 12 '22 at 17:01

0 Answers0