Working with Modules and Packages

A short Python program can happily live in a single file—but as soon as you write a larger program, you need a way to organize its code. Above functions, Python has two more levels of code organization: functions and other code live in modules, and modules live in packages. Let’s start by looking at modules.

Defining and Importing Modules

A module defines entities such as constants and functions that you can import and use in a program. Aside from some of the in-built modules of the Python interpreter, a module is a Python file.

For example, here is a module named my_module.py:

 THE_ANSWER = 42
 
 
 def​ ​ask​():
 return​ THE_ANSWER

This file defines a function and a constant. ...

Get Programming Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.