Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Hour 13. Working with Modules


What You’ll Learn in This Hour:
What a module is
Standard Python modules
What a module contains
How to create a custom module

Keeping your Python scripts a reasonable size helps you use and manage them. Modules can help you
keep a Python script to a reasonable size. In this hour, you will learn about modules: how to create
them and how to use them in your Python scripts.


Introducing Module Concepts


A module is a collection of functions. You learned about writing your own functions in Hour 12,
“Creating Functions,” and started using functions, such as print, in Hour 4, “Understanding Python
Basics.” A module is external to a Python script and has to be imported using the import statement.
Once it is imported, the function or functions the module contains are available for you to use within
your script. The module you import may be a standard module, such as the os module. A module may
also be a user-created module, which is a module that contains functions a user (such as you) wrote.


By the Way: Term Confusion
Because a module contains functions, you often see the terms function and module
used interchangeably in Python books and documentation. Also, a function within a
module is sometimes called a method or an operation.

A module must be imported before a function in its collection can be used. However, there are three
flavors of Python modules:


Python functions stored in a .py file—These modules can be either locally available (via the
Python standard library) or downloaded from somewhere else.
C programs that are dynamically loaded into the Python interpreter—These modules are
built-in.
C programs that are linked with the Python interpreter—These modules are built-in.

To determine a particular module’s flavor, you start by viewing the modules housed in files that end
with .py. At the shell prompt, issue the command ls /usr/lib/python/.py on your
Raspbian system. You then see the various versions of Python installed, along with each version’s
modules stored in files.


Viewing linked modules is a little trickier. You need to import the sys module to display a list of the
built-in modules, as shown in Listing 13.1. Notice that the math module is listed here.


LISTING 13.1 List of Built-in Python Modules

Free download pdf