lgd
lgd

Reputation: 1462

using "as" breaks imports in python?

Why does this work fine in python 2.x:

>> import matplotlib
>> import matplotlib.pylab

while this doesn't?

>> import matplotlib as mp
>> import mp.pylab
ImportError: No module named mp.pylab

isn't as just a short hand/alias for the module being used? it doesn't make sense that the first case works and second doesn't. why does it happen?

you can do same with os/path (from @kevin):

>> import os as o
>> import o.path
ImportError: No module named o.path

Upvotes: 2

Views: 104

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113988

when you say

import foo.bar

you are essentially describing an import file path it will look for foo/bar.py or foo/bar/__init__.py

you could mimic this to see by creating

test.py

x=5

test2.py

import test.x

you will see an error about no module x

this has nothing to do with aliasing imports with as nor does it have anything to do with matplotlib ...

it is what the import statement does, it describes where to find the file

ergo when you type

import mp.pylab

you are telling the filesystem to look for mp/pylab.py or mp/pylab/__init__.py (of coarse neither of those exists)

LARGE DISCLAIMER

this is probably a gross oversimplification

Upvotes: 2

Related Questions