Imports into __init__.py file

Asked

Viewed 558 times

1

I’m studying the documentation of Django and noticed that in some files __init__.py there are imports, I know the archive __init__.py defines a module but do not understand why imports in it.

2 answers

3


The archive __init__.py is the entry point package.

When you do, for example:

from django import *

What you are importing will be the context set in django/__init__.py - limited, of course, by the object __all__ if this is set in the file. This is precisely for you to work with the scope that is made available to users of the package.

Note, for example, that if you do:

from django import get_version

You can import the function get_version successfully, even if the function is not even declared in django/__init__.py. What happens is that in the file __init__.py of Django there is the instruction:

from django.utils.version import get_version

What matters the function from where it is declared to the scope in __init__.py and thus also being available directly in the scope of the package.

The Flask library also does this, to make basic classes available in a more direct way:

__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 excerpt taken from official repository of Flask

  • Thanks again for the excellent reply.

1

(Another example, although they have already answered)

They help with code organization. We usually import more 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 we have in a directory with 20 figures . py that use a sum() and subtraction() function of a file called posses_funcao_soma.py and posses_funcao_subtracao.py of the subdirectory. Instead of writing to all 20 files

from subdiretorio.possui_funcao_soma import soma
from subdiretorio.possui_funcao_subtracao import subtracao

We wrote:

#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 don’t need 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.