FREE Courses
Text

Packages and Modules

Lesson 12

To clearly organize large projects into logical units, Python structures code into modules and packages.

A module is the base unit of Python’s program structure. A module is a file with a .py extension that contains all the functions, classes and definitions pertaining to that module.

A package is a collection of modules all saved inside a package folder. The package folder must contain a file called __init__.py for Python to be able to identify the folder as a package.

Let’s have a look at the Django project we created in the last chapter to see packages and modules in action:

\mfdw_site
    init .py    # This tells Python that
                # mfdw_site is a package.
    settings.py	# The settings module for our project. 
    urls.py     # The urls module for our project.
    # ...

The Dot Operator

Dot notation is a common idiom in object-oriented programming. I like to think of the dot like a point because the dot points to something. In the case of Python, the dot operator points to the next object in the object chain. In Django classes, the object chain is like this:

package.module.class.method

Or in the case of functions:

package.module.function.attribute

Some real-life examples:

  • forms.Form points to the Form class in the forms package.
  • pages.apps.PagesConfig points to the PagesConfig class in the apps sub-package of the pages package. I.e., the apps.py file in you pagesapp.
  • django.conf.urls points to the urls package inside the conf package inside django which is also a Python package!

This can sometimes get a bit confusing, but if you remember to join the dots (sorry, bad pun there), you can usually find out what the dot operator is referring to.

Lesson Resources

Pen