When is from
and import
used? How does the two lines differ? What do they do?
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
When is from
and import
used? How does the two lines differ? What do they do?
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
The first line imports the specific class ListedColormap
from matplotlib.colors
package.
The second line gives an alias plt
to the package matplotlib.pyplot
so that you can call any function or class of the package as plt.func()
import module
This imports the entire module. In this instance to access any functions defined in the module you would need to use "module.function"
from module import part_of_module
This imports a part of a module e.g. a class or function.
If you add the alias e.g.
import pandas as pd
Then you can access pandas functions etc. using e.g. pd.DataFrame rather than pandas.DataFrame, for brevity/convenience to call it what you want.
It is also an option, but not recommended, to go
from module import *
This imports the entire module, but if you want to use a function from that module you no longer need to explicitly state module.function in order to use it. This is not recommended because you could have multiple functions with the same name which could result in calling the wrong function.
from matplotlib.colors import ListedColormap
Import a specific class from a package.
import matplotlib.pyplot as plt
Import the package as an aliased package name.