Home > Software engineering >  Can't import module with location set to PYTHONPATH in Python
Can't import module with location set to PYTHONPATH in Python

Time:11-26

I've checked other answers on SO as well, but they don't seem to be like mine.

So I'm playing around with imports, and I decided to put my module custom.py into a nested folder like this: /Users/alex/Desktop/Learn/mods/onemore/custom.py

My main script file is in the following location: /Users/alex/Desktop/Learn/main.py

So when I do import custom in main.py, I get the error ModuleNotFoundError: No module named 'custom'

This happens despite the fact that /Users/alex/Desktop/Learn/mods/onemore is in PYTHONPATH:

> echo $PYTHONPATH

> /Users/alex/Desktop/Learn/mods/onemore

and also the path is visible in sys.path (the second one):

> ['', '/Users/alex/Desktop/Learn/mods/onemore', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages']

Why can't I still import the module?

CodePudding user response:

You can import it with folder name Ex: from onemore import custom

CodePudding user response:

You need to add an empty __init__.py file at /Users/alex/Desktop/Learn/mods/onemore to call in this manner (as a regular package).

else if it's in the python path, call it as a namespace package (no need for init):

from custom import <func-you-need>

The standard for imports is currently from PEP420.

  • Related