9

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?

asked Nov 9, 2017 at 2:47
1
  • 1
    Packages are containers for modules and other subpackages. In your example x is the package and y the module, similar to "from the shopping bag take the apple", not the other way around. Commented Nov 9, 2017 at 2:51

2 Answers 2

15

x may be a package or a module and y is something inside that module/package.

A module is a .py file, a package is a folder with an __init__.py file. When you import a package as a module, the contents of __init__.py module are imported.

answered Nov 9, 2017 at 2:53
Sign up to request clarification or add additional context in comments.

7 Comments

Packages don't necessarily have an __init__.py file, and modules aren't necessarily .py files.
You don't need __init__.py file in Python 3 and module maybe anything since import hooks were invented but these are exception for the above conventions. 99% of the time the above applies.
Thank you for the explanations! This helps!
@geckos Could you please elaborate on those exceptions? Can you add a link for the import hooks? The official python docs state "The init.py files are required to make Python treat directories containing the file as packages.". Are the docs outdated?
|
7

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
answered Nov 13, 2017 at 2:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.