The python modules are a type of a file, which contains statements and definitions. In python, there are mainly two types of the python modules, built-in python modules, and user-defined python modules.
What are Python Modules?
Python modules are used to reuse the code and it is also used to write and maintain large programs. They also provide a way to separate implementation details from the rest of the program, making it easier to understand and modify the code.
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 has a large number of built-in modules, which are used to make tasks easy and more readable. These modules provide a wide range of functionality and are always available for use without the need to install any additional packages.
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:
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, this article will help you to understand what python modules are and the types of the python modules. In addition, you will be able to understand how to use built-in python modules and how to create user-defined python modules and use those modules in another python program.
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.