6

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.

Jeon
  • 4,000
  • 4
  • 28
  • 73

2 Answers2

6

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!

perimosocordiae
  • 17,287
  • 14
  • 60
  • 76
0

It seems that in the __init__.py of a module, it can use a variable __all__ to control what variables or functions to be imported in the current scope when you write a statement looks like: from modulename import * ; I thinks it also works for the syntax import modulename;In the __init__.py file of numpy, I find the following code:

__all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
zhujs
  • 543
  • 2
  • 12