0% found this document useful (0 votes)
2 views12 pages

Chapter 3.2 Python Modules & Package

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Chapter 3.2 Python Modules & Package

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 3.

2 :Python modules and


packages

[Link] GAIKAR
Python modules
In Python, modules and packages are the primary building
blocks for organizing and reusing code.
1. Python Modules :
Module Definition: A module is a single file with a .py extension
containing Python definitions and statements. It serves as a
container for related functions, global variables, and classes.
Creation: Any Python file you create is essentially a module. For
instance, saving code as [Link] creates a module named calc.
Usage: You use the import statement to access a module's
content in another script.
Standard Modules: Python includes a large Standard Library of
built-in modules like math, os, and sys

[Link] GAIKAR
Python modules
In Python, modules and packages are the primary building blocks for
organizing and reusing code.
1. Python Modules :
A module in Python is a file that contains Python code (functions, variables,
classes) which can be reused in other programs.
 A module is a single file with a .py extension containing Python definitions
and statements. It serves as a container for related functions, global
variables, and classes.
Creation: Any Python file you create is essentially a module. For instance,
saving code as [Link] creates a module named calc.
Usage: You use the import statement to access a module's content in
another script.
Standard Modules: Python includes a large Standard Library of built-in
modules like math, os, and sys

[Link] GAIKAR
Modules in Python
What is a Module?
A module in Python is simply a file containing Python code (functions, variables,
classes) that you can reuse in other programs.
👉 Example: A file named math_utils.py is a module.

Why Modules Matter (Real


Reason)Facts: Help
break large programs into smaller parts
Enable code reuse
Improve readability & maintenance Opinion (practical
reality):
If you’re not using modules in real projects, your code will
quickly become messy and unscalable.
📘 Types of Modules in Python
🔹 1. Built-in Modules (Standard Library)
🔹 2. User-defined Modules
These are modules created by the user to organize and reuse code.
Built-in Modules
These modules are already available in Python, so you don’t need to install
them. Examples:
1. Mathematical Modules 5. String & Text Processing
math → Mathematical functions (sqrt, factorial, pi) re → Regular expressions
cmath → Complex number operations string → String constants
random → Random numbers textwrap → Text formatting

2. Date & Time Modules 6. Internet & Networking


datetime → Date and time handling urllib → URL handling
time → Time-related functions http → HTTP operations
calendar → Calendar operation socket → Network communication
3. File & System Modules 7. Debugging & Development
os → Operating system interaction logging → Logging events
sys → System-specific parameters unittest → Unit testing
shutil → File operations (copy, move) traceback → Error tracking
4. Data Handling Modules 8. GUI Programming
json → JSON data handling tkinter → GUI applications
csv → CSV file handling
pickle → Object serialization
Example: Built-in Modules
✅ Code:
import math
print([Link](16)) # Square root
print([Link](5)) # Factorial
✔ Output:
4.0
120

2. Example: Using Random Module


import random
print([Link](1, 10))
# Random number between 1 and 10
2. User-defined Modules
These are modules created by the user to organize and reuse code.

💻 Example 1: 📄 Main file:


📄 File: [Link]
import mymodule
def add(a, b): print([Link](5, 3)) # Output:
return a + b 8

💻 Example 2: 📄 Step 2: Main program


📄file : [Link] import mymodule
[Link]("Dipak")
def greet(name): print([Link](5, 3))
print("Hello", name)

def add(a, b):


return a + b

[Link] GAIKAR
Different way to Importing modules
1. Basic Import :Importing the module directly requires you to use the full tkinter.
prefix for every widget.
import tkinter
You must use the module name every time
Example: root= [Link]()
2. Import with Alias (Best Practice): This is the standard approach for modern
Python applications because it keeps the namespace clean while being quick to
type
import tkinter as tk
Example: root=[Link]()
3. Import Specific function :
from tkinter import Tk, Label, Button
Only selected components are imported
👉Makes code more controlled and readable
Example: root = Tk()
4. Import All (*)
from tkinter import *
👉 Imports everything from tkinter
Example: root = Tk() [Link] GAIKAR
Python Packages
Package Definition: A package is a directory that contains multiple modules.
This hierarchical structure allows for a "dotted module name" namespace
(e.g., A.B refers to submodule B in package A).

The __init__.py File: For a directory to be recognized as a Regular Package, it


must contain a special file named __init__.py.
Recognition: It marks the folder as a package so the interpreter can find its
modules.
Initialization: Code inside __init__.py runs automatically the first time the
package is imported.
Control: It can define the __all__ variable to specify which modules are
imported when using from package import *.

[Link] GAIKAR
Comparison Summary module vs package
Feature Module Package
Physical A single .py file A directory (folder)
Form

Contents Functions, classes, One or more modules and


and variables sub-packages

Identifier Filename Directory name


(without .py)
__init__.py
Special File None (required for regular
packages)

Key Components of a Python Package


•Module: A single Python file containing reusable code (e.g., [Link]).
•Package: A directory containing modules and a special __init__.py file.
•Sub-Packages: Packages nested within other packages for deeper
organization.
[Link] GAIKAR
Creating and Accessing Packages
Create a Directory: create a folder that will act as the package root.
Add Modules: Inside the directory, add Python files (modules). Each
module can contain related functions or classes.
Add __init__.py: add an __init__.py file to the directory. This file tells
Python that the directory should be treated as a package.
Create Sub-packages (Optional): One can organize code further by
creating subdirectories with their own __init__.py files.
Import Modules: Modules or functions inside the package can be
imported using dot notation, for example:

[Link] GAIKAR
Example In this example, we create a package called math_operations to organize
mathematical functions. The package contains two sub-packages:
•basic: addition and subtraction
•advanced: multiplication and division Each operation is stored in its own module, which
makes the code modular, reusable and easier to maintain.

[Link] GAIKAR

You might also like