The difference between import and from import in Python is:
- import imports the whole library.
- from import imports a specific member or members of the library.
For example, let’s import the
datetime module as a whole:
import datetime d1 = datetime.date(2021, 10, 19)
In comparison, let’s only import the
date class from the
from datetime import date d1 = date(2021, 10, 19)
Using from import can save you from repeating the module name when you need to refer to it many times in the code.
When Use ‘import’ and When ‘from import’
Use from import when you want to save yourself from typing the module name over and over again. In other words, when referring to a member of the module many times in the code.
Use import when you want to use multiple members of the module.
To make any sense of it, let’s see some useful examples.
Let’s say you are creating multiple date objects using the
import datetime d1 = datetime.date(2000, 1, 1) d2 = datetime.date(2010, 1, 31) d3 = datetime.date(2008, 5, 17) d4 = datetime.date(1992, 2, 18) d5 = datetime.date(1899, 6, 22)
There is a lot of repetition because you call
datetime.date many times.
To avoid repetition, import the
date class directly from the
from datetime import date d1 = date(2000, 1, 1) d2 = date(2010, 1, 31) d3 = date(2008, 5, 17) d4 = date(1992, 2, 18) d5 = date(1899, 6, 22)
This way you save time and lines of code by not having to repeat the module name over and over again.
Let’s say you want to perform different mathematical operations in your code.
In this case, import the
math module as a whole:
import math x = 10 y = 4 d = math.sqrt(x ** 2 + y ** 2) r = 5.0 area = math.floor(math.pi * r ** 2)
Import a Bunch of Members from a Module
Now you know how to import a specific member from a module in Python.
But what if you need a bunch of them?
To import multiple members from a module, call from import by comma-separating the member names.
For instance, let’s import
floor from the
from math import sqrt, floor x = 5.2 y = 2.4 d = floor(sqrt(x ** 2 + y ** 2))
Today you learned what is the difference between import and from import in Python.
- Use from import to target a specific member (or members) of the module that you are going to repeat in the code.
- Use import to import the module as a whole
Thanks for reading.