0

I'm working on a Python project with the following directory structure:

lunarcity/
├── main.py
└── modules/
    ├── __init__.py
    ├── config.py
    ├── voice.py
    ├── manager.py
    └── other_module.py

In the main.py file, I have a handle_voice_message function that is supposed to import and use functions from the voice.py file located in the modules directory. Additionally, voice.py imports functions from config.py and manager.py, both of which are also in the same modules directory.

However, when I run the main.py file, I encounter the following error: ModuleNotFoundError: No module named 'config'

I have tried various import methods, including both direct imports like import config and relative imports like from . import config, but none of them seem to resolve the issue. It's worth mentioning that I have added the __init__.py file to the modules directory to make it a package.

I have already tried:

  1. Checking for typos in the file names and import statements.
  2. Ensuring that the init.py file is present in the modules directory to make it a package.
  3. Trying both direct and relative import statements in voice.py.

Despite all these efforts, I still can't seem to import the modules from the same directory. I'm puzzled by this behavior, and I don't understand why the imports are not working as expected...

  • i have run into these problems. Basically, my conclusion is python does not handle this well as it opens the code to **circular references**... so i will be interested to see if an alternative answer is posted. – D.L Jul 18 '23 at 21:38
  • 1
    @D.L Check out the update I've made to the post. It contains the solution that helped me. Maybe it can help you too. – hikaru-k-bit Jul 18 '23 at 23:48
  • good work, it is better to post as a new answer as opposed to an update of the problem. – D.L Jul 19 '23 at 08:08
  • @D.L Thank you for your suggestion. – hikaru-k-bit Jul 19 '23 at 13:50

1 Answers1

0

Update [The problem fixed]

In my case, the solution was to import the bot variable from the manager.py file. As the bot was initialised twice, the nonsensical errors came out. Now this is fixed and it works smoothly.

main.py

import datetime
import time
import mysql.connector
import openai
from apscheduler.schedulers.background import BackgroundScheduler
from pytz import timezone
from modules.config import load_config
from modules.manager import bot  # add the import statement
from modules.voice import voice_message

manager.py

import telebot
from .config import load_config

config_data = load_config()

bot = telebot.TeleBot(config_data['bot_token'])

ALTERNATIVE

It seems that the reason for the error was also a missing dot before importing a file from the same directory. So if you encounter the same problem, please check that your import syntax is from .x import y, not from x import y.