How to import a single function from a Python module?



In Python, the module is a file containing Python definitions and statements. For keeping the code organized, we often write functions in separate modules and import them into main program.

While importing the entire module, sometimes we only need a single function from it. Python provides a direct way to do this using the from module_name import function_name syntax.

Importing sqrt() from math module

In this approach, we are going to use from math module importing the sqrt to import only the sqrt function.

The Python sqrt() function is used to calculate the square root of the number. As it is the part of the math module, we need import this module before using this function.

Example

Let's look at the following example, where we are going to calculate the square root of the number.

from math import sqrt
print(sqrt(121))

The output of the above program is as follows -

11.0

Importing choice() from random module

In this approach we are going to import only the choice() function from the random module.

The Python choice() function is used to to select the random elements from the given sequence (such as list, tuple or string). Here we are going to use this function with the list and randomly select one element from it.

Example

In the following example, we are going to randomly select the elements from the list using the choice() function.

from random import choice
print(choice(['Ciaz', 'Cruze', 'Chiron']))

The following is the output of the above program -

Chiron

Importing datetime() from datetime module

The third approach is by importing only the datetime class from the datetime module. Here we are going to use the datetime.now() method to get the current date and time.

The Python datetime.now() method is used to return the current local date and time as a datetime object.

Example

Consider the following example, where we are going to get the current local time and date.

from datetime import datetime
print(datetime.now())

The following is the output of the above program -

2025-05-09 15:09:22.279717
Updated on: 2025-08-28T13:06:30+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements