Python Modules is a separate program that has its own functions and code. We can say the module is the same as a code library that contains a set of functions, if you want, you can use it in your application.
Here is Import a Module lesson, and more.
The Advantage of use Python Modules is
- It’s broken down large programs into small manageable and organized files.
- Modules provide the reusability of code.
- Using an inbuilt or third-party module(library) can reduce time and effort.
Create a Python Modules
You just need to save the code in python file (extension .py
), it will be a module.
Module file named mymodule.py
, This is a custom module example.
def message(msg): print("Module print, " + msg)
How to import modules in Python?
By using the import
statement, you can use the module mymodule.py
, like this example.
In Hello.py import the module and passing the value to “message” function of “mymodule“.
import mymodule mymodule.message("Hello")
Output: Module print, Hello
Variables in Module
All type of variables like lists, dictionaries, objects etc can define in module and access form other python class.
Example :
Module file mymoduel.py with a list variable
varList = ['a', 1, 'b', 2]
importing file in Hello.py print(), accessing list variable and in the console.
import mymodule print(mymodule.varList)
Output : [‘a’, 1, ‘b’, 2]
Import Standard Modules of Python
Import is searched for the module initially in the local scope by calling __import__()
function.
math module is a standard module of python.
import math print(math.factorial(5))
Output: 120
For a complete tutorial with example follow the “How Python Import-Module“.
Bonus: Also read: the example of File handling in python: Delete File, used an import the OS module to delete a file in python.
Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All Python Modules Example are in Python 3, so it may change its different from python 2 or upgraded versions.