I'm playing around with matplotlib to understand its structure better and I'm confused by the following piece of code:
import matplotlib as mpl
from mpl import pyplot as plt # ModuleNotFoundError : No module named 'mpl'
mpl.pyplot # AttributeError: module 'matplotlib' has no attribute 'pyplot'
If on the other hand I abstain from importing matplotlib as
a different name and execute instead
import matplotlib
from matplotlib import pyplot as plt #works!
the things work.
Even more crazy, if I "combine" these two import matplotlib as mpl from matplotlib import pyplot as plt #works! mpl.pyplot.get_backend() # works
I can curiously access attributes from pyplot
even if I reference it as mpl.pyplot
.
What is going on here, why does
from mpl import pyplot as plt
throws aModuleNotFoundError
?import mpl.pyplot
not work? Since the error message indcates thatmpl
was correctly resolved tomatplotlib
, yet stillpyplot
couldn't be found...referencing
pyplot
asmpl.pyplot
not cause an error in my last example?
(Note that I do know of course that the preferred way is to import pyplot
as import matplotlib.pyplot as plt
but the point of my investigation is precisely to understand what fails and why when I ventured outside the welltrodden streets of code.)
mpl
package which doesn't exist – Wiesempl
) util a spec for the module is returned or all finders on sys.meta_path have been tried (fullname as string, later normally the same as__name__
). With this the finder (normally) just searches the sys.path for python classes / modules named that way. Once a finder has found and returned the spec the Loader will be called to create / execute the imported module itself. – Wieseas
, then the name followingas
is bound directly to the imported module" and 2) "Thefrom
form uses a slightly more complex process: find the module specified in thefrom
clause, loading and initializing it if necessary". – Kenwaympl
is already "associated" to thematplotlib
module and therefore usingfrom mpl [...]
, thatmpl
should be resolved to thematplotlib
module? – Kenwayimport
.) – Kenway