0

The question is old and has been asked many times, yet I'm not able import my own module. What am I missing?

python3 --version

rm --recursive --force /tmp/mypython
mkdir --parents --verbose /tmp/mypython/test
cd /tmp/mypython/test/

touch /tmp/mypython/__init__.py

printf "def myfunction():
    print('foo')" > /tmp/mypython/mymodule.py

printf "import mymodule
mymodule.myfunction()" > /tmp/mypython/test/mytest.py

tree /tmp/mypython/

python3 mytest.py

Returns:

Python 3.9.1
mkdir: created directory '/tmp/mypython'
mkdir: created directory '/tmp/mypython/test'
/tmp/mypython/
├── __init__.py
├── mymodule.py
└── test
    └── mytest.py

1 directory, 3 files
Traceback (most recent call last):
  File "/tmp/mypython/test/mytest.py", line 1, in <module>
    import mymodule
ModuleNotFoundError: No module named 'mymodule'
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
jjk
  • 592
  • 1
  • 6
  • 23
  • 2
    `from .. import mymodule`, you might have to add an `__init__.py` to the test directory as well – RJ Adriaansen Jan 30 '21 at 20:38
  • Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. – Belhadjer Samir Jan 30 '21 at 21:16
  • @RJAdriaansen `from .. import mymodule` and adding `__init__.py` to /test doesn't help: `ImportError: attempted relative import with no known parent package` – jjk Jan 31 '21 at 08:53

1 Answers1

0

Starting from Python 3.3, implicit relative references are allowed no more. That means that the ability to reference a module in the parent directory is not possible .They were removed because of concerns about ambiguity, and especially package behavior changing unexpectedly because of other, third packages being installed. link

after each executing of python script the current directory automatically added to PYTHONPATH ,which is an envirenoment variable that contain the list of packages that will be loaded .which contains the list of packages that will be loaded by Python upon execution.

Solution

you have to add the parent directory the PYTHONPATH

import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
#then import you module 
import my_module 
Belhadjer Samir
  • 1,461
  • 7
  • 15
  • File "/tmp/mypython/test/mytest.py", line 7, in import my_module ModuleNotFoundError: No module named 'my_module' – jjk Mar 30 '21 at 08:10