159

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?

Dark Templar
  • 6,223
  • 16
  • 46
  • 46
  • 1
    Regarding why it's the not the other way around, see http://stackoverflow.com/questions/3600352/reasoning-behind-from-import-syntax-in-python –  Oct 01 '11 at 23:40
  • 2
    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 '18 at 15:47
  • A related concept to know - [Classes vs. modules in Python](https://softwareengineering.stackexchange.com/q/329348/236257) – RBT Jul 23 '18 at 05:40

1 Answers1

215

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
Yam Marcovic
  • 9,270
  • 2
  • 27
  • 29
  • 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 02 '11 at 04: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 02 '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 04:18
  • Probably a bit too esoteric to be worth it, in retrospect – holdenweb Apr 22 '17 at 16:08