pythonimportpython-importimporterrorcircular-dependency

Is there a way to solution this circular import in Python?


I'm making a simple discord bot for a friend and college, just for fun. The bot is an assistant for playing role games. I'm having a circular import problem. Any clues on how to solve it?

The code in the "bot.py" file The code in the "bot_commands.py" file

The error message:

Traceback (most recent call last):
  File "C:\Users\Jvlian\Workspace\discord-bot\discod-bot-role-assistant\bot.py", line 28, in <module>
    from bot_commands import bot_commands
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Jvlian\Workspace\discord-bot\discod-bot-role-assistant\bot_commands.py", line 6, in <module>
    from bot import bot, session, Character
  File "C:\Users\Jvlian\Workspace\discord-bot\discod-bot-role-assistant\bot.py", line 28, in <module>
    from bot_commands import bot_commands
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ImportError: cannot import name 'bot_commands' from partially initialized module 'bot_commands' (most likely due to a circular import) (C:\Users\Jvlian\Workspace\discord-bot\discod-bot-role-assistant\bot_commands.py)

I tried before changing the names of the files but it didin't work. The can run smothly, until I need to use commands


Solution

  • Your circular import can be solved by removing one of the imports. You should remove the import from your bot_commands.py because you can't register your commands to your bot if you don't import them in your bot.py file.

    First, refactor your bot_commands.py. After removing your from bot import bot, session, Character, put every command into one function so that you can take your bot, session, and Character as arguments. Here's an example with your first two commands:

    def add_commands(bot, session, Character):
        @bot.command()
        async def hello(ctx):
            await ctx.send("Hola, bienvenido :D")
    
        @bot.command()
        async def goodbye(ctx):
            await ctx.send("Nos vimos, te kiero muxo :D")
        
        #add your other commands in this function as well
    
    

    Then in your bot.py, since you still have your from bot_commands import bot_commands, you can just add add_commands(bot, session, Character) before your bot.run(BOT_TOKEN). This will import all your commands and initialize them while providing them with your bot, session, and Character variables.