Python modules and packages are essential concepts for understanding how to structure and organize your Python code. Though often used interchangeably, modules and packages are actually distinct entities with different purposes. In this tutorial, we'll explore the difference between modules and packages in Python. Whether you're a beginner or an experienced Python developer, mastering these concepts will help you write cleaner, more efficient, and more scalable code. So, let's dive in and explore the world of modules and packages in Python!

Table of Contents :

  • Modules in Python
  • Packages in Python 
  • Difference between Modules and Packages in Python

Modules in Python :

  • A module is a single file that contains Python definitions, functions, and statements.
  • It is used to break up large programs into smaller, more manageable parts.
  • Modules are imported using the  import  statement followed by the module name.
  • Example:

def greeting(name):
   print("Hello, " + name)
def farewell(name):
   print("Goodbye, " + name)

import module_example

Packages in Python :

  • A package is a way to organize related modules into a single parent directory/folder.
  • It can contain one or more sub-packages, which can also contain other sub-packages.
  • Packages are created by adding a special file called  to a directory.
  • Example:

# my_package/
from . import module1
from .sub_package import module2
__all__ = ["module1", "module2"]

import my_package.module1
from my_package.sub_package import module2

Difference between Modules and Packages in Python :

  • A module is a single file, while a package is a directory that can contain multiple modules.
  • Modules are loaded into memory when they are imported, while packages need to be initialized by executing the  file.
  • Modules cannot have sub-modules, while packages can have one or more sub-packages.
  • Modules are imported using the  import  statement, packages are also imported using the  import  statement, but the package name is followed by module name separated by a dot.

Prev. Tutorial : Creating packages

Next Tutorial : Datetime module