Python: How to import from an __init__.py file?
12,425
Try relative imports
from . import db
Author by
kramer65
Updated on June 05, 2022Comments
-
kramer65 almost 2 years
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 usingfrom __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! -
jwg about 7 yearsThis does not answer the question.
-
TomSawyer over 6 yearsif i use
from . import *
will it import everything inside__init__.py
or all files inside the current folder? -
Heisenberg almost 6 yearsHow come
from .
knows to look inside__init__.py
? -
tynn almost 6 yearsThe
.
path is relative for current package. The__init__.py
defines the current package and what to export.