I'm building a website using the Flask Framework, in which I've got a folder in which I have some python files and an __init__.py
script (I guess you would call this folder a module?). In the init.py file I've got a line saying:
db = Database(app)
I now want to use db
in a different script which is in this folder. Normally I would do this using from __init__ import db
, but that just doesn't seem right to do, let alone pythonic. Furthermore, since it is in the __init__.py
file, I suppose it should somehow be initialised for the whole folder/module.
Does anybody know how I can use db
from the __init__.py
file? All tips are welcome!
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.
The sole purpose of __init__.py is to indicate that the folder containing this file is a package, and to treat this folder as package, that's why it is recommended to leave it empty.
Try relative imports
from . import db
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