When I try to use pyplot
from matplotlib
:
import matplotlib
print matplotlib.pyplot # just checking
It gives me AttributeError: 'module' object has no attribute 'pyplot'
It can be solved with:
import matplotlib.pyplot
But what I am really confused with is,
import numpy
print numpy.random
gives me <module 'numpy.random' from '/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/numpy/random/__init__.pyc'>
What is the difference between two cases? pyplot
cannot be called in the first example, but random
was in the second. I think it's related with some kind of packages and modules. But I'm not such a professional to the python, thus asking for an answer.
For the definitive tutorial, read this.
But for your specific case, it looks like this is what's happening:
Every directory-based python module (like matplotlib
and numpy
) has an __init__.py
file, which determines what is brought into the module's top-level scope. By default (when __init__.py
is empty), nothing is in scope.
However, some modules (like numpy
) have decided to hoist functionality into the top-level by adding import statements to __init__.py
. This brings those submodules into scope, even if you've only explicitly imported numpy
.
To check our assumptions, let's look at the source!
__init__.py
doesn't include the statement import pyplot
.__init__.py
does include import random
, on line 176.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With