Terminal
$ ls
foo.py
$ cat foo.py
print("Inside of foo")
$ python3.10
Python 3.10.4 (main, Apr 8 2022, 17:35:13) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
Inside of foo
>>> exit()
$ ls
foo.py __pycache__
$ mv foo.py ../
$ ls
__pycache__
$ ls -R
.:
__pycache__
./__pycache__:
foo.cpython-310.pyc
$ python3.10
Python 3.10.4 (main, Apr 8 2022, 17:35:13) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'foo'
>>>
What am I trying to do above:
created file foo.py
foo.py
print("Inside of foo")
When I import foo.py it created foo.cpython-3.10.pyc file inside of pycache directory then I removed foo.py and again tried to import foo.py it raising error ModuleNotFoundError.
According to python official document for python3.10 the import mechanism flowchart
if matching foo.pyc is found? is yes then it will load foo.pyc?
Why getting ModuleNotFoundError even if foo.pyc file present in pycache directory?
I have visited SO link which similar to this question where one of the answer is below.
If there's no source, python will automatically import .pyc
Please visit this link for PEP-3147 where more information can be found regarding the import flow chart and import mechanism.