Search code examples
pythonpython-3.xmodularitytelebot

No module named 'config' when importing from the same directory in Python project


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...


Solution

  • 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.