Difference between a module and a package

suggest change

Modules

A module is a single Python file that can be imported. Using a module looks like this:

module.py

def hi():
    print("Hello world!")

my_script.py

import module
module.hi()

In an interpreter

>>> from module import hi
>>> hi()
# Hello world!

Packages

A package is made up of multiple Python files (or modules), and can even include libraries written in C or C++. Instead of being a single file, it is an entire folder structure which might look like this:

Folder package

__init__.py

from package.dog import woof
from package.hi import hi

dog.py

def woof():
    print("WOOF!!!")

hi.py

def hi():
    print("Hello world!")

A regular package contains an __init__.py file. Namespace packages, available since Python 3.3, do not. When you import a regular package (import package), its __init__.py file is run. In this case, that file imports woof and hi, so you can call package.woof and package.hi.

Putting a package in a ZIP file

It is possible to put a Python package in a ZIP file and import it that way if the archive contains the package and you add these lines to the beginning of your script:

import sys
sys.path.append("package.zip")

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents