Python: How to import from an __init__.py file?

12,425

Try relative imports

from . import db
Share:
12,425
kramer65
Author by

kramer65

Updated on June 05, 2022

Comments

  • kramer65
    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 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!

  • jwg
    jwg about 7 years
    This does not answer the question.
  • TomSawyer
    TomSawyer over 6 years
    if i use from . import * will it import everything inside __init__.py or all files inside the current folder?
  • Heisenberg
    Heisenberg almost 6 years
    How come from . knows to look inside __init__.py?
  • tynn
    tynn almost 6 years
    The . path is relative for current package. The __init__.py defines the current package and what to export.