Modules & Packages


Module

A module is a single Python file containing reusable code (functions, classes, variables)
  1. File with .py extension
  2. Can be imported using import module_name
  3. Provides code reusability and organization
Example:
We created the module with the name of operations.py

def add(a, b):
    a+b
def subtract (a, b):
    a-b
We are going to use functions in operations.py file via import.

import operations as op
addition = op.add(3,4)
print(addition)

Package

A package is a collection of modules organized in directories with a special __init__.py file.
  1. Directory containing Python files
  2. Must contain __init__.py (can be empty)
  3. Can have sub-packages (nested directories)
Example:
my_package/
│   __init__.py
│   module1.py
│   module2.py
└───subpackage/
    │   __init__.py
    │   module3.py
Import Type Syntax Description
Module Import import module Imports entire module (access with module.function())
Specific Import from module import function Imports specific function/class directly
Package Import import package.module Imports module from a package
Alias Import import module as md Imports with an alias name