Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 331
kramer65 Avatar asked Mar 09 '14 12:03

kramer65


People also ask

What does an __ init __ py file do?

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.

How do I import a Python 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.

What is the use of file __ init __ py in a package even when it is empty?

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.


1 Answers

Try relative imports

from . import db
like image 66
tynn Avatar answered Sep 28 '22 01:09

tynn