Stack Overflow Asked by Will Waltrip on November 30, 2020
I have the below file structure:
Project
app.py
package_A
__init__.py
a_module.py
package_B
__init__.py
b_module.py
package_C
__init__.py
c_module.py
packageD
__init__.py
d_module.py
within d_module.py
I am running the following import command:
from package_C.c_module import someFunc
I am continually getting a ModuleNotFoundError: No module named 'package_C'
. I have tried a number of different things from using a pipenv shell within the project directory, adding a Pipfile
to the project directory. Also creating a virtual environment.
Right now the app.py file is empty as I am just starting the project, is the issue?
I'm guessing that the __init__.py
in the package_C
folder is blank?
Just putting an __init__.py
in the a package folder does not automatically give you access to all modules within the package. You only get access to the modules that are imported in the __init__.py
file.
This is because when you import a package python runs all the modules in the __init__.py
file and adds them to the symbol table.
If you add import c_module
in the __init__.py
file, you should be able to import any objects from c_module
.
Answered by pykam on November 30, 2020
For IDE like pycharm will automatically add parents directory to path, thus when ran manually it won't find packages as it's not listed in parents directory.
See this example:
# file: B.__init__.py
try:
from A import a
print("IDE import")
except ImportError:
from os import getcwd
from sys import path
path.append(getcwd() + "/..")
from A import a
print("without IDE")
print(a)
Output - in IDE:
IDE import
<module 'A.a' from 'Z:\github\StackOverFlow\A\a.py'>
Output in terminal:
without IDE
<module 'A.a' from 'Z:\github\StackOverFlow\B/..\A\a.py'>
And this also changes when directory is nested once more in project directory, in that case it will always import with path insertion used in except
block.
Answered by jupiterbjy on November 30, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP