Reputation: 65
I have a repo with a Flask webapp and a separate python directory, and I'm using PyCharm.
My project directory is:
/backup/
__init__.py
python modules etc
/webapp
/py
__init__.py
/lib
__init__.py
python code
/src
__init__.py
python code
/static
js, css, fonts etc
/templates
html
webapp.py
I'm trying to import a module into webapp.py. This module exists in webapp/py/src/blah.py. blah.py has a class called Blah. I'm trying to write blah = Blah()
before I import the module. I want pycharm to import it when I hit option + return. When I try importing through pycharm it imports it like this:
from webapp.py.src.blah import Blah
This doesn't work since webapp isn't a python package. When I change it to
from py.src.blah import Blah
it works. Is there any way I can get it to import properly? I believe I've had it working before. Then a group member decided almost every directory needed an __init__.py
and I think that may have messed up pycharm. I tried flushing the cache but it doesn't work. Any solutions?
Upvotes: 0
Views: 1347
Reputation: 127200
The webapp directory, as shown, is not a Python package. It does not contain an __init__.py
file, therefore it cannot be included in an import path. You appear to have set up your Python path so that the webapp directory is on the path, which is why packages under it are importable (the py directory).
So this is a problem with how you've structured your project, not with PyCharm. For an example of the "right" way to structure a Flask app and related data, see the source code for Python chat room's website: https://github.com/sopython/sopython-site.
Basically, you need to run from the directory that should be on your path, each of the packages should be within this directory (and should be packages with __init__.py
). Neither myapp or backup should be on the Python path, only project.
/project
/run.py
/myappp
__init__.py
/backup
__init__.py
Upvotes: 1