Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to import a single function from a Python module?
In Python, a module is a file containing Python definitions and statements. For keeping code organized, we often write functions in separate modules and import them into the 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, which is more memory-efficient and cleaner than importing the whole module.
Syntax
from module_name import function_name
This imports only the specified function, making it available directly without the module prefix.
Importing sqrt() from math Module
The sqrt() function calculates the square root of a number. Instead of importing the entire math module, we can import only sqrt() ?
from math import sqrt
result = sqrt(121)
print("Square root of 121:", result)
Square root of 121: 11.0
Importing choice() from random Module
The choice() function selects a random element from a sequence like list, tuple, or string ?
from random import choice
cars = ['Ciaz', 'Cruze', 'Chiron', 'Camaro']
selected_car = choice(cars)
print("Randomly selected car:", selected_car)
Randomly selected car: Cruze
Importing datetime Class from datetime Module
The datetime class provides methods to work with dates and times. We can import just this class instead of the entire datetime module ?
from datetime import datetime
current_time = datetime.now()
print("Current date and time:", current_time)
Current date and time: 2024-01-15 14:30:45.123456
Importing Multiple Functions
You can also import multiple functions from the same module in one line ?
from math import sqrt, pow, ceil
print("Square root of 16:", sqrt(16))
print("2 raised to power 3:", pow(2, 3))
print("Ceiling of 4.2:", ceil(4.2))
Square root of 16: 4.0 2 raised to power 3: 8.0 Ceiling of 4.2: 5
Comparison
| Import Method | Syntax | Usage | Best For |
|---|---|---|---|
| Entire Module | import math |
math.sqrt(16) |
Using many functions |
| Single Function | from math import sqrt |
sqrt(16) |
Using few functions |
| Multiple Functions | from math import sqrt, pow |
sqrt(16), pow(2,3) |
Specific functions only |
Conclusion
Use from module_name import function_name to import specific functions for cleaner code and better memory efficiency. This approach is ideal when you need only a few functions from a module rather than importing everything.
