A python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module.
A file containing Python code, for example: example.py, is called a module
We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.
A file containing a set of functions you want to include in your application.
How to create module in python?
To create a module just save the code you want in a file with the file extension .py:
In this example, we will create a module named as file.py which contains a function func that contains a code to print some message on the console.
Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.
How to Use a Module in python?
we can use the module by using the import statement
We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.
The import statement
The import statement is used to import all the functionality of one module into another.
We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into our file.
import module1,module2,........ module n
Import the module named mymodule, and call the displayMsg function:
Example
Variables in Module
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
The from-import statement
Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from? import statement.
Main File
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our python source file.
The syntax to rename a module is given below.
import <module-name> as <specific-name>
dir() function
The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and functions defined in this module.
Trending Tutorials