Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between importing python sub-modules from NumPy, matplotlib packages [duplicate]

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.

like image 791
Jeon Avatar asked Apr 03 '14 14:04

Jeon


1 Answers

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!

  • matplotlib's __init__.py doesn't include the statement import pyplot.
  • numpy's __init__.py does include import random, on line 176.
like image 182
perimosocordiae Avatar answered Oct 23 '22 04:10

perimosocordiae