I am studying the documentation of Django
and I noticed that in some __init__.py
files there are imports, I know that the __init__.py
file defines a module but I do not understand why it imports.
I am studying the documentation of Django
and I noticed that in some __init__.py
files there are imports, I know that the __init__.py
file defines a module but I do not understand why it imports.
The __init__.py
file is the entry point of the package.
When you do, for example:
from django import *
What you are importing will be the context defined in django/__init__.py
- obviously limited by the __all__
object if it is defined in the file. This is just for you to work with the scope that is available to package users.
Note, for example, that if you do:
from django import get_version
You will be able to successfully import the get_version
function, even if the function is not even declared in django/__init__.py
. What happens is that in the __init__.py
file of Django there is the statement:
from django.utils.version import get_version
It imports the function where it is declared for scope in __init__.py
and thus also available directly in the scope of the package.
The Flask library also does this, to make basic classes more direct:
__version__ = '1.1.dev'
# utilities we import from Werkzeug and Jinja2 that are unused
# in the module but are exported as public interface.
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from jinja2 import Markup, escape
from .app import Flask, Request, Response
from .config import Config
Code snippet taken from the official Flask repository
(Another example, even though they have already replied)
They help organize the code. We usually import most commonly used functions and classes into __init__.py
.
Given this architecture:
diretorio_1/
__init__.py
arquivo.py
arquivo2.py
arquivo3.py
...
arquivo20.py
subdiretorio/
__init__.py
possui_funcao_soma.py
possui_funcao_subtracao.py
Imagine that we have a directory with 20 .py files that use a sum () and subtract () function from a file called has_funcao_soma.py and has_funcao_subtracao.py from the subdirectory. Instead of writing in all 20 files
from subdiretorio.possui_funcao_soma import soma
from subdiretorio.possui_funcao_subtracao import subtracao
We write:
#No __init__.py do subdiretorio
from possui_funcao_soma import soma
from possui_funcao_subtracao import subtracao
#Nos 20 arquivos do diretorio
from subdiretorio import soma, subtracao
One advantage of doing this is that you do not have to keep checking where the function you want to import is, it can be accessed easier if it has already been imported into __init__.py
.