0
0
Pythonprogramming~5 mins

Importing specific items in Python

Choose your learning style9 modes available
Introduction

Importing specific items lets you bring only the parts you need from a module. This keeps your code clean and uses less memory.

When you only need a few functions or classes from a large module.
To avoid naming conflicts by importing only what you want.
To make your code easier to read by showing exactly what you use.
When you want to reduce the startup time of your program by loading less code.
Syntax
Python
from module_name import item1, item2, ...
You can import multiple items by separating them with commas.
Imported items can be functions, classes, or variables.
Examples
This imports only the sqrt function from the math module.
Python
from math import sqrt
This imports the date and time classes from the datetime module.
Python
from datetime import date, time
This imports randint but renames it to random_int for easier use.
Python
from random import randint as random_int
Sample Program

This program imports sqrt and pi from the math module. It calculates the square root of 16 and then uses that as the radius to find the area of a circle.

Python
from math import sqrt, pi

number = 16
root = sqrt(number)
circle_area = pi * (root ** 2)

print(f"Square root of {number} is {root}")
print(f"Area of circle with radius {root} is {circle_area}")
OutputSuccess
Important Notes

Importing specific items helps avoid loading the whole module, which can save memory.

You can rename imported items using as to avoid name clashes or for convenience.

If you import many items, consider if importing the whole module might be clearer.

Summary

Use from module import item to bring in only what you need.

This keeps your code clean and can improve performance.

You can import multiple items and rename them for clarity.