The Quick Python Book, Fourth Edition cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

18 Packages

 

This chapter covers

  • Defining a package
  • Creating a simple package
  • Exploring a concrete example
  • Using the __all__ attribute
  • Using packages properly

Modules make reusing small chunks of code easy. The problem comes when the project grows and the code you want to reload outgrows, either physically or logically, what would fit into a single file. If having one giant module file is an unsatisfactory solution, having a host of little unconnected modules isn’t much better. The answer to this problem is to combine related modules into a package.

In this chapter, we discuss Python packages as structure of directories and files on disk.

Note

Quite often people speak of a “package” that combines one or more Python modules or packages into a single distributable file that can be uploaded to a package repository like PyPI, which is mentioned in the next chapter. There is an ever-increasing array of options for creating such packages, and that process is beyond the scope of this book A good starting point for learning how to create distributable Python packages would be the Python Packaging User Guide, which can be found at https://packaging.python.org/en/latest/.

18.1 What is a package?

A module is a file containing code. A module defines a group of usually related Python functions or other objects. The name of the module is derived from the name of the file.

18.2 A first example: mathproj

18.3 Implementing the mathproj package

18.3.1 __init__.py files in packages

18.3.2 Basic use of the mathproj package

18.3.3 Loading subpackages and submodules

18.3.4 import statements within packages

18.4 The __all__ attribute

18.5 Proper use of packages

18.6 Creating a package

18.6.1 Solving the problem with AI-generated code

18.6.2 Solutions and discussion

Summary