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.
The __init__.py file lets the Python interpreter know that a directory contains code for a Python module . An __init__.py file can be blank. Without one, you cannot import modules from another folder into your project. The role of the __init__.py file is similar to the __init__ function in a Python class.
Within __init__.py , we import all the modules that we think are necessary for our project.
Although Python works without an __init__.py file you should still include one. It specifies that the directory should be treated as a package, so therefore include it (even if it is empty).
Any directory with an __init__.py file is considered a Python package. The different modules in the package are imported in a similar manner as plain modules, but with a special behaviour for the __init__.py file, which is used to gather all package-wide definitions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With