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

Question:

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!

Asked By: kramer65

||

Answers:

The init.py files are automatically imported when you import the package they are in. For example, say the init.py is in a package called foo. When you import foo

import foo
from foo import *
import foo as ...

the init file gets called. And are you using python 2 or 3? If you are using python 3, you will need to use dynamic imports:

from * import __init__

In general, it is a bad practice to import from init, I would suggest trying to place this code in another file in the package.

Answered By: wcb98

Try relative imports

from . import db
Answered By: tynn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.