CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Modules – A quick walkthrough

When we write a Python program and save that program into a file, that file we can call it as a Module. A module in Python is nothing but a group of statements and definitions, saved into a file. Each module has a purpose. Each module contains group of definitions or functions and statements, exported to use them in other modules or programs to perform particular operations. 

Modules are useful to group the related functionalities and use them when required by importing into the program. We use import statement, to import the modules into the program. Python modules are saved with a file extension of .py.

For example, if we keep the functionalities of accounting, put all the related functionalities into a file, an accounting module, and import the module into other modules or programs when required to perform accounting related operations.

The file name is the module name; and we can get the module name in the module by using the global variable __name__ .

Standard Modules in Python

Python provides standard modules. We can import them into our program by using import statement, like below.

import <module name>

Some of these modules are built into the Python interpreter; hence no need to import them explicitly into the program.

To find out list of methods or definitions exported from the module, we can use dir(<module name>) function. For example, dir(sys) statement returns all the names defined in the sys module.

Variants of import

With the above import statement, we can import all the definitions from the module. Python supports variants of import; allows us to import specific definition(s) from the module instead of importing all the definitions from the module. For that we need to use from statement.

Simplified form of it, looks like below;

from <module name> import <definition>

With that, we can use only the imported definitions from the module.

/Shijit/

Python – Modules – A quick walkthrough

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top
Exit mobile version