Search code examples
djangodesign-patternsfacade

The `__init__.py` import multiple modules while they are not utilized within the file


I am reading /django/forms/__init__.py

"""
Django validation and HTML form handling.
"""

from django.core.exceptions import ValidationError  # NOQA
from django.forms.boundfield import *  # NOQA
from django.forms.fields import *  # NOQA
from django.forms.forms import *  # NOQA
from django.forms.formsets import *  # NOQA
from django.forms.models import *  # NOQA
from django.forms.widgets import *  # NOQA

The __init__.py import multiple modules while they are not utilized within the files.

I assume they might be employed by others lived in the same dir, How Django achieve this?


Solution

  • The __init__.py import multiple modules

    s/modules/names/ - the from somemodule import somename syntax exposes the somename name, not somemodule.

    while they are not utilized within the files. I assume they might be employed by others lived in the same dir

    Actually this is a design pattern known as "facade" - the forms package hides it's inner implementation (in which submodule / subpackage is something defined) so

    1/ the users can just import what they need from django.forms without having to care about the underlying modules / subpackages hierarchy,

    and

    2/ the mainainers can reorganize the underlying modules / subpackages hierarchy without breaking client code.

    How Django achieve this?

    This is nothing Django specific, it's just plain ordinary Python. Read Python's doc about modules and packages.