The difference between import and from import in Python is:
- import imports an entire code 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 datetime module:
from datetime import date d1 = date(2021, 10, 19)
Now you can directly call the imported date function instead of accessing it via datetime.date.
Using from import can save you from repeating the module name when you need to use its code many times in your code project.
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, use from import 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.
Example 1. Creating Multiple Instances
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 datetime module.
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.
Example 2. Calling a Function Once
Let’s say you want to perform different mathematical operations in your code.
In this case, you can import the math module as a whole and call the different math operations from the module:
import math x = 10 y = 4 d = math.sqrt(x ** 2 + y ** 2) r = 5.0 area = math.floor(math.pi * r ** 2)
In this example, you only call math.sqrt and math.floor once, so it might not be necessary to separately import these functions with the from import statement.
But once again, if you need these functions more often than once in your project, then perhaps you should import the functions separately.
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 sqrt and floor from the math module:
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. Happy coding!