Last Updated on July 13, 2023 by Mayank Dham
Python modules are files that consist of statements and definitions. In the Python programming language, there exist two primary categories of modules: built-in modules provided by Python itself and user-defined modules created by programmers.
What are Python Modules?
Python modules serve multiple purposes, including code reuse and facilitating the development and maintenance of large programs. They offer a means to separate implementation details from the main program, resulting in improved code readability and modifiability. By utilizing modules, developers can effectively organize and manage their code, promoting reusability and enhancing the overall efficiency of the programming process.
Python Modules can contain functions, classes, variables, and other objects, and can be imported into other programs to be used. The definitions and statements in a module can be accessed by other programs by using the import statement, followed by the name of the module. Python also provides several built-in modules that are always available for use, and users can create their own modules by saving their functions and variables in a file with a .py extension.
Now, let’s see what python modules look like with an example:
# user.py
def login(username):
return "Welcome, " + username + "!"
def logout(username):
return "Have a nice day, " + username + "!"
Here we have created a python module user.py with two functions login and logout. Let’s see how we can use the above module in other programs.
# main.py
import user
print(user.login("PrepBytes"))
print(user.logout("PrepBytes"))
In the above code, we have imported the module user using the import keyword. After that, we used both the functions of the user module.
Output:
Welcome, PrepBytes!
Have a nice day, PrepBytes!
Types of Python Modules
There are two types of python modules:
- Built-in python modules
- User-defined python modules
1. Built-in modules:
Python boasts an extensive collection of built-in modules designed to simplify tasks and enhance code readability. These modules offer a diverse range of functionality and are readily accessible without the requirement of installing extra packages. With these built-in modules, Python provides a comprehensive set of tools and capabilities right out of the box, allowing developers to accomplish various tasks conveniently and without the hassle of additional installations.
A list of a few most frequently used built-in python modules is given below
- math: This module is very useful to perform complex mathematical functions such as trigonometric functions and logarithmic functions.
- date: The date module can be used to work with date and time such as time, date, and datetime.
- os: Provides a way to interact with the underlying operating system, such as reading or writing files, executing shell commands, and working with directories.
- sys: Provides access to some variables used or maintained by the Python interpreter, such as the command-line arguments passed to the script, the Python version, and the location of the Python executable.
Example of built-in python modules.
# Example using the os module import os print(os.getcwd()) print(os.listdir()) # Example using the sys module import sys print(sys.version) print(sys.argv) # Example using the math module import math print(math.pi) print(math.sin(math.pi / 2)) # Example using the json module import json data = { "name": "John Doe", "age": 30, "city": "New York" } json_data = json.dumps(data) print(json_data) # Example using the datetime module import datetime now = datetime.datetime.now() print(now) print(now.year) print(now.month) print(now.day) # Example using the re module import re text = "The quick brown fox jumps over the lazy dog." result = re.search(r"fox", text) print(result.start(), result.end(), result[0]) # Example using the random module import random print(random.randint(1, 100)) print(random.choice([1, 2, 3, 4, 5]))
Output:
/home/bEO6qL
['prog']
3.9.5 (default, Nov 18 2021, 16:00:48)
[GCC 10.3.0]
['./prog']
3.141592653589793
1.0
{"name": "John Doe", "age": 30, "city": "New York"}
2023-02-06 11:21:49.354873
2023
2
6
16 19 fox
17
5
2. User-defined modules in Python:
User-defined python modules are the modules, which are created by the user to simplify their project. These modules can contain functions, classes, variables, and other code that you can reuse across multiple scripts.
How to create a user-defined module?
We will create a module calculator to perform basic mathematical operations.
# calculator.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
In the above code, we have implemented basic mathematic operations. After that, we will save the above python file as calculator.py.
Now, we will use the above user-defined python module in another python program.
# main.py
import calculator
print("Addition of 5 and 4 is:", calculator.add(5, 4))
print("Subtraction of 7 and 2 is:", calculator.sub(7, 2))
print("Multiplication of 3 and 4 is:", calculator.mul(3, 4))
print("Division of 12 and 3 is:", calculator.div(12, 3))
Output:
Addition of 5 and 4 is: 9
Subtraction of 7 and 2 is: 5
Multiplication of 3 and 4 is: 12
Division of 12 and 3 is: 4.0
How to import python modules?
We can import python modules using keyword import. The syntax to import python modules is given below.
Syntax to Import Python Modules
import module_name
Example to Import Python Modules:
import math
print(math.sqrt(4))
Output:
2.0
In the above program, we imported all the attributes of module math and we used the sqrt function of that module.
Now, let’s see how we can import specific attributes from the python module.
To import specific attributes or functions from a particular module we can use keywords from along with import.
Syntax to import python module using Attribute:
from module_name import attribute_name
Example of import python module using Attribute:
from math import sqrt
print(sqrt(4))
Output:
2.0
Now, let’s see how we can import all the attributes or functions from the module at the same time.
We can import all the attributes or functions from the module at the same time using the * sign.
Syntax to import python module using all Attributes:
from module_name import *
Example to import python module using all Attributes:
from math import *
print(sqrt(4))
print(log2(8))
Output:
2.0
3.0
Conclusion
In conclusion, Python modules are instrumental in code reuse, program organization, and enhancing the functionality of Python programs. They enable developers to separate implementation details, improve code readability, and maintain large-scale projects effectively. With a vast collection of built-in modules, Python provides a rich ecosystem of functionalities, making it easier to accomplish a wide range of tasks without the need for additional package installations.
FAQs Related to Python Modules
1. What are the different types of Python modules?
There are two main types of Python modules: built-in modules and user-defined modules. Built-in modules are modules that come preinstalled with Python, while user-defined modules are modules that you create yourself.
2. Can you import multiple modules into a Python script at once?
Yes, you can import multiple modules into a Python script by using multiple import statements. For example, you can write import module1, module2, module3 to import three modules at once.
3. Can we rename a module when you import it into a Python script?
Yes, you can rename a module when you import it into a Python script by using the as the keyword. For example, you can write import module1 as m1 to import the module1 module under the name m1.
4. Can we only import specific functions or classes from a module in Python?
Yes, you can import specific functions or classes from a module in Python by using the from keyword. For example, you can write from module1 import function1 to import the function1 function from the module1 module.
5. What happens if two modules have a function or class with the same name?
If two modules have a function or class with the same name, you need to qualify the names of the functions or classes from each module to avoid ambiguity. For example, if both module1 and module2 have a function named function1, you would write module1.function1() and module2.function1() to call the functions from each module, respectively.
6. Can you import a module that is in a different directory in Python?
Yes, you can import a module that is in a different directory in Python by adding the directory to the sys.path list. This will make Python look in the specified directory for modules when you run an import statement.
7. Can you import a module from the Internet in Python?
Yes, you can import a module from the Internet in Python by using a package manager, such as pip, to install the package that contains the module. Once the package is installed, you can import the module in your script just like any other module.