Whenever I do from 'x' import 'y' I was wondering which one is considered the 'module' and which is the 'package', and why it isn't the other way around?

  • 1
    Regarding why it's the not the other way around, see stackoverflow.com/questions/3600352/… – user7043 Oct 1 '11 at 23:40
  • 1
    I, for one, am thankful for this question, because the answer is concise and gives the exact needed knowledge. The documentation is all fine and dandy, but it's verbose and contains waaay more information than what the OP was asking for, and certainly more than I needed. I just wanted an answer to that specific question, and the answer below is exactly what I wanted. Many of us just don't need such formal or in-depth answers. – Teekin Mar 24 at 15:47
  • A related concept to know - Classes vs. modules in Python – RBT Jul 23 at 5:40
up vote 186 down vote accepted

A Python module is simply a Python source file, which can expose classes, functions and global variables.

When imported from another Python source file, the file name is treated as a namespace.

A Python package is simply a directory of Python module(s).

For example, imagine the following directory tree in /usr/lib/python/site-packages:

mypackage/__init__.py <-- this is what tells Python to treat this directory as a package
mypackage/mymodule.py

So then you would do:

import mypackage.mymodule

or

from mypackage.mymodule import myclass
  • Aha, so when you say that the file name is treated as a namespace, you would so something like this? "mymodule.var1" for the first case, or "myclass.var1" for the second? – Dark Templar Oct 2 '11 at 4:08
  • 1
    Not exactly. The package still counts as part of the namespace. If you want to do what you said then you need to do from mypackage import mymodule. – Yam Marcovic Oct 2 '11 at 10:42
  • It might be useful to add something about namespace packages, for which the code need not necessarily all appear inthe same directory tree. – holdenweb Apr 19 '17 at 16:59
  • @holdenweb Never used the different mechanisms involved there directly, so not an expert. If you provide a detailed explanation about it in a new answer, I'll refer to it from mine. – Yam Marcovic Apr 22 '17 at 4:18
  • Probably a bit too esoteric to be worth it, in retrospect – holdenweb Apr 22 '17 at 16:08

protected by gnat Feb 5 at 12:09

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.