Class 12: Using Libraries

By: Archana Shukla and Rajesh Shukla

PYTHON MODULES

Here we will learn:

What are the modules in Python?
How to import modules in Python?
Python import statement
Import with renaming
Python from…import statement
Import all names
Python Module Search Path
Reloading a module
The dir() built-in function

 

What are the modules in Python?

In python, Modules refer to a file containing Python statements and python function definitions.

Modular programming refers to the process of breaking a large programming task into separate, smaller, more manageable subtasks or modules.

Individual modules can then be cobbled together like building blocks to create a larger application.

There are several advantages of modules while developing a large application:

* On dividing the large program into a number of small modules, the program becomes easy/simple to understand.

* development process becomes easier and less error-prone.

* different modules are independent of each other. (We may make changes to a module without having any knowledge of the application outside that module.)

* Reusability: Functionality defined in a single module can be easily reused

* This eliminates the need to recreate duplicate code.(code once is written can be reused again and again)

The import Statement

Module contents are made available to the caller with the import statement. The import statement takes many different forms, shown below.

1.
The simplest form of using import statemnet as shown below:

Syntax:
import <module_name>

2.
An alternate form of the import statement allows individual objects from the module to be imported directly into the caller’s file.

Syntax:
from <module_name> import <name(s)>

3.
Several comma-separated modules may be specified in a single import statement:

Syntax:
import <module_name>[, <module_name> …]

4.
It is even possible to indiscriminately import everything from a module at one fell swoop:

Syntax:
from <module_name> import *

This will place the names of all objects from <module_name> into the local symbol table, with the exception of any that begin with the underscore (_) character.

5.
It is also possible to import individual objects but enter them into the local symbol table with alternate names:

Syntax:
from <module_name> import <name> as <alt_name>
from <module_name> import <name> as <alt_name>[, <name> as <alt_name> …]

This makes it possible to place names directly into the local symbol table but avoid conflicts with previously existing names:

syntax:
import <module_name> as <alt_name>

You can also import an entire module under an alternate name:

Syntax:
import <module_name> as <alt_name>