O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Modules

As your programs grow in size, you’ll probably want to break them into multiple files for easier maintenance. To do this, Python allows you to put definitions in a file and use them as a module that can be imported into other programs and scripts. To create a module, put the relevant statements and definitions into a file that has the same name as the module. (Note that the file must have a .py suffix.) Here’s an example:

# file :  div.py
def divide(a,b):
    q = a//b        # If a and b are integers, q is an integer
    r = a - q*b
    return (q,r)

To use your module in other programs, you can use the import statement:

import div
a, b = div.divide(2305, 29)

The import statement creates a new namespace that contains all the objects defined in the module. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required