Home > Articles > Programming > Python

  • Print
  • + Share This
This chapter is from the book

2.19 Modules

A module is a logical way to physically organize and distinguish related pieces of Python code into individual files. A module can contain executable code, functions, classes, or any and all of the above.

When you create a Python source file, the name of the module is the same as the file except without the trailing .py extension. Once a module is created, you may import that module for use from another module using the import statement.

How to Import a Module

import module_name

How to Call a Module Function or Access a Module Variable

Once imported, a module’s attributes (functions and variables) can be accessed using the familiar dotted attribute notation:

module.function()
module.variable

We will now present our Hello World! example again, but using the output functions inside the sys module.

>>> import sys
>>> sys.stdout.write('Hello World!\n')
Hello World!
>>> sys.platform
'win32'
>>> sys.version
'2.4.2 (#67, Sep 28 2005, 10:51:12) [MSC v.1310 32 bit
(Intel)]'

This code behaves just like our original Hello World! using the print statement. The only difference is that the standard output write() method is called, and the NEWLINE character needs to be stated explicitly because, unlike the print statement, write() does not do that for you.

You can find out more information on modules and importing in Chapter 12.

We will cover all of the above topics in much greater detail throughout the text, but hopefully we have provided enough of a “quick dip in the pool” to facilitate your needs if your primary goal is to get started working with Python as quickly as possible without too much serious reading.

  • + Share This
  • 🔖 Save To Your Account