Pycharm error: 'No Module' when trying to import own module (python script)
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.
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:
- Flex your fingers onto the terminal.
- Authenticate with
echo $PYTHONPATH
(Unix) orecho %PYTHONPATH%
(Windows). - 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:
- Brace yourself, head to File > Settings > Project ... > Project Interpreter.
- Click the gear icon, select More, and then the Show paths for the interpreter button. Off to the races.
- 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.
Was this article helpful?