Having some issues with importing modules in python. This is my folder structure
my_app/
app.py
__init__.py (I want to import a function from this file)
folder1/
__init.py
method1.py
folder2/
__init__.py
method.py
In my root __init__.py I have this function
def want_to_be_run_elsewhere():
pass
In my app.py, I want to import this function and run it when I start my application, but I'm unsure how to do it.
from my_app import want_to_be_run_elsewhere
This throws a no module named my_app
From what I can tell, I have all the necessary __init__.py files, so maybe it could be sys.path related?
I've read some similar threads on here but I haven't been able to solve this.
1 Answer 1
Usually you would do the import like
from . import want_to_be_run_elsewhere
This doesn't work here, because you are calling app.py. If you import my_app.app, it is part of the module. If you call it it is not. Importing from the module it is in using . will then not work.
You could either move app.py outside of my_app, removing it from the module and making imports work again.
Or you can use
from __init__ import want_to_be_run_elsewhere
in app.py
I believe
from my_app import want_to_be_run_elsewhere
will only work if you have actually pip install -e my_app/. Then it should work too.
2 Comments
app.py as a module in the package: From the dir above my_app, call python -m my_app.app or python3 -m my_app.app. See stackoverflow.com/a/11536794/674064 from __init__ import .... It's not the right way of doing things. It can even break code if some code in the submodules depends on the package name (e.g. if you use modules like pickle directly or shleve etc using that solution will make data unreadable).
app.pyand__init__.pyinsidemy_app/or not?app.pyand__init__.pyis inside my_app/ andapp.pyis my entry point__init__.pyfile. They are normally empty, or just have an__all__list in them.