Explain Codes LogoExplain Codes Logo

Pycharm error: 'No Module' when trying to import own module (python script)

python
prompt-engineering
best-practices
venv
Anton ShumikhinbyAnton Shumikhin·Mar 3, 2025
TLDR

Stumbled upon the 'No Module' nuisance in PyCharm? That’s likely because your script's directory isn't recognized on the PYTHONPATH. To put things in place, all you need to do is right-click the directory containing your module in the Project side-bar, navigate to 'Mark Directory as' > 'Sources Root'. This move flags the directory, placing it onto Python's search path. Voila! PyCharm can now detect your module.

# Assuming this is your structure: # project_folder/ # --> mymodule.py (your mysterious module) # --> script.py (the script that's shouting 'where is my module') # In script.py: import mymodule # And... The error disappears!

Make sure your import statement matches the actual directory format. If it still isn't importing, red-check the syntax used for importing.

Probe Beyond just 'Sources Root'

System's PYTHONPATH to the Rescue

Besides marking the directory as Sources Root, ensure PYTHONPATH in the system configuration isn't acting all aloof:

  1. Flex your fingers onto the terminal.
  2. Authenticate with echo $PYTHONPATH (Unix) or echo %PYTHONPATH% (Windows).
  3. Invisible? Add it manually via environment variables or within PyCharm’s interpreter settings.

Project Configuration Settings

Dive into the project settings via File > Settings > Project: [project name] > Project Structure. Ensure your directories aren't playing hide and seek, check if they have been selected correctly.

All's well with Virtual Environment?

Check if your current virtual environment lines up with where the module resides. If PyCharm is using a differently located interpreter, the No Module issue is bound to see the light.

Init Files and Package Structure

It's time to __init__.py a check for these files in the directory structure. Python checks these to know the directories housing packages. Hence, they are cardinal for importing.

Diving Deeper into PyCharm's Project Structure

Under the Hood: Project Structure Settings

Venture into File > Settings > Project ... > Project Structure. Check if directories are rightfully marked as Content Root or Sources Root. PyCharm can be just as confused with a messed up structure.

PYTHONPATH Modifications Made Easy

Need to tweak the PYTHONPATH? Here’s how:

  1. Brace yourself, head to File > Settings > Project ... > Project Interpreter.
  2. Click the gear icon, select More, and then the Show paths for the interpreter button. Off to the races.
  3. You can now add or remove paths.

Cache Clearance to the Rescue

PyCharm keeps a cache of project interiors. Renovation leads to confusion. So, we invalidate the cache and restart by navigating to File > Invalidate Caches / Restart.