Modules Vs Packages In Python — Learn the Difference Under A Minute

The terms module & package are defined differently by different programming languages. This caused some confusion to me while switching from another language to python. Here’s how these terms are used in the context of python.

This is me every time I encounter some new stuff in Python

A) Module

A module is a single Python file that can be imported.

Let’s create a module with name module.py which has function hi().

module.py

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

Now, in another file my_script.py, we can use the import module shown below.

my_script.py

import module
module.hi()

B) 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
  • hello.py
  • world.py

__init__.py

from package.hello import print_hello
from package.world import print_world

hello.py

def print_hello():
   print(“Hello”)

world.py

def print_world():
   print("World!")

All Python packages must contain a __init__.py file. When you import a package into your file, the __init__.py script will run which gives you access to the all of the functions in the package. In this case, it allows you to use the package.hello and package.world functions.

Get new blog posts delivered straight to your inbox. No Spam. I Promise.

Email *


You may also like

2 Comments

  1. Shilpa – Thanks for this. In the end you said, “In this case, it allows you to use the package.hi and package.woof functions.” but you actually mean package.hello and package.world, correct?

    Raj

Leave a Reply

Your email address will not be published. Required fields are marked *