14

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!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
kramer65
  • 50,427
  • 120
  • 308
  • 488
  • possible duplicate of [Importing files in Python from \_\_init\_\_.py](http://stackoverflow.com/questions/1201115/importing-files-in-python-from-init-py) – BoshWash Mar 09 '14 at 12:49

2 Answers2

24

Try relative imports

from . import db
tynn
  • 38,113
  • 8
  • 108
  • 143
0

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.

wcb98
  • 172
  • 1
  • 1
  • 10