11
votes

So I am confused as what the difference is...Here is some code to display my confusion:

>>> import collections.OrderedDict as od
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named OrderedDict
>>> from collections import OrderedDict as od
>>> od
<class 'collections.OrderedDict'>

explanation:

import collections.OrderedDict did not find the module, yet from collections import OrderedDict found it?! What is the difference between those two statements?

the class is read as collections.OrderedDict, so I don't understand why the first attempt was unable to find the module

note:

I am simply using collections as an example. I am not looking for specifically why my example acted the way it did for collections, but rather an explanation for what the different lines of code are actually requesting as far as imports go. If you would like to include an explanation on the error, feel free! Thanks!

2
OrderedDict is a class within the collections module. When you see things like x.y and something is being imported from it, that means that "y" in this case is actually a module. - wheaties
oh so basically y would be a directory inside x in the scheme of things where otherwise y is a class or function inside the module? - Ryan Saxe
you can nest modules within modules, yes. - wheaties
i knew that, I just didn't realize that this was actually different syntax - Ryan Saxe
Hey, no worries. It actually made me pause as well. Great question. - wheaties

2 Answers

7
votes

OrderedDict is a class within the collections module. When you see things like x.y and something is being imported from it, that means that "y" in this case is actually a module.

You should read the docs about how import works: here. It's long and involved but at the same time fairly straight forward in how it looks into the different packages and modules to find what should be brought into play. Specifically, the import statement itself and import system.

4
votes

PEP 221 talks about import as.

import foo.bar

is for importing a submodule bar of the module foo. This can be 'imported as'

import foo.bar as fb

An object is imported

from foo import baz

This, too, can be 'imported as'

from foo import baz as fb

collections.OrderedDict is not a submodule but an object so it can only be 'imported as' in the second way.