skip to Main Content

I am relatively new to python, I started learning the language in October 2023 and used VS Code as my IDE.

In my test automatoin project I had put all of my classes into one folder (Classes for error handling, setup and teardown of webdrivers, etc etc),I realised I should properly structure my files once it had reached 2000 lines and was still growing.

When attempting any imports from another directory, I would recieve the following error to the console.

from ReskinRefactor.handlers import driver_handler
ModuleNotFoundError: No module named 'ReskinRefactor'

Around two weeks ago I switched to using PyCharm as python is the main language that I am using, and doing the exact same thing runs the files and imports all modules completely fine, my file structure is below:

├───ReskinRefactor
    │   utils.py
    │   __init__.py
    ├───handlers
    │   │   driver_handler.py
    │   │   error_handler.py
    │   │   log_handler.py
    │   │   test_handler.py
    │   └───__init__.py
    |
    ├───make_things
    │   │   create.py
    │   │   delete.py
    │   └───edit.py
    │
    └───test_files
        │
        └───Accounts
            │   playeground.py   
            └───__init__.py

I have tried both relative and absolute imports on both IDE’s and I am confused as to why PyCharm handles this code and why VS Code doesn’t.

I would rather learn that I have bad code than accept that one IDE makes my bad code work.

2

Answers


  1. It’s because VS Code didn’t create the __init__.py file at the root of your project and PyCharm does.

    If you want to import functions/classes/etc from your file.py, there must be a __init__.py file.

    For example, if your root directory is Lib, and it has a main.py and src directory with myfile.py (with function f), then you must to add __init__.py in the Lib directory and in the src directory. Then, in main.py you can type:

    from Lib.src.myfile import f
    
    Login or Signup to reply.
  2. You could open your settings, then search for "Execute In File Dir". Uncheck this option may work.

    When you uncheck this option, the terminal will use the currently opened workspace as the root directory to run the file, rather than the folder where the file is located.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search