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: The file must have a .py suffix.) For 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) 

import creates a new namespace that contains all the objects defined in the module. To access this namespace, ...

Get Python Essential Reference, Second Edition 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.