Python Libraries and Modules - Organising Code
Organising Classes with Modules and Packages
As the number of classes increases, it becomes essential to organize them effectively for accessibility and maintainability. Creating a well-structured codebase is crucial for good code.
Modular Programming
Modular programming involves dividing a large programming task into smaller, manageable subtasks or modules. This approach offers several advantages:
- Simplicity: Modules simplify code by breaking it into smaller, understandable units.
- Maintainability: Changes in one module are less likely to affect other parts of the code.
- Reusability: Modules can be reused in different parts of the application or in other projects.
- Scoping: Modules provide namespaces that help avoid naming conflicts.
In Python, modules are simple files. If two files are in the same folder, you can load a class from one module into another for use.
Packages
Packages are folders that contain modules. They help to organize projects by grouping related modules together, preventing a cluttered structure. To create a package, include a file named __init__.py in each folder that should be treated as a package. This file can be empty but must exist.
Using Python Modules
Example: Importing a Class
Consider a Point class defined in a file named point_docstrings.py. To use this class in another file, you can import it:
import point_docstrings
p1 = point_docstrings.Point()
Namespace
When you import point_docstrings into another program, point_docstrings becomes part of the calling program’s namespace. The namespace includes all methods and classes available to the current program.
Importing Specific Classes
To import only a specific class from a module, use the from keyword:
from point_docstrings import Point
p1 = Point()
Renaming Imported Classes
If a class with the same name already exists in the current namespace, you can use the as clause to rename the imported class:
from Pointdocstrings import Point as Pt
p1 = Pt()
Importing Multiple Classes
To import multiple classes from a module, list them after the import keyword:
from Pointdocstrings import Point, Line
To import all classes from a module, use the * wildcard:
from Pointdocstrings import *
Using Python Packages
Package Structure Example
parent_directory/
├── main.py
├── Drawing/
│ ├── __init__.py
│ ├── point_call.py
│ └── point_docstrings.py
└── Maths/
├── __init__.py
└── Theorem.py
Absolute vs. Relative Imports
- Absolute Imports: Specify the full path to the module or class.
- Relative Imports: Specify the location relative to the current package.
Absolute Import Examples
# Method 1
import Drawing.point_call
P1 = Drawing.point_call.Point()
# Method 2
from Drawing.point_call import Point
P1 = Point()
# Method 3
from Drawing import point_call
P1 = point_call.Point()
Relative Import Examples
.refers to the current directory (package)...refers to the parent directory (package).
If Point-call.py wants to call Point-docstrings.py within the same Drawing package, you can use a relative import:
from .Point_docstrings import Point
If Theorem.py in the Maths package wants to call Point-docstrings.py in the Drawing package, you can use:
from ..Drawing.Point_docstrings import Point
Popular Libraries
Python has a vast collection of libraries available on the Python Package Index (PyPI): https://pypi.org/
Exercise 1: Matplotlib
Use the matplotlib library (https://pypi.org/project/matplotlib/) to create a line chart visualizing monthly sales data.
Instructions:
- Import the
matplotlib.pyplotmodule. - Create two lists:
- Months:
['January', 'February', 'March', 'April', 'May', 'June'] - Sales:
[2500, 2700, 3000, 2800, 3200, 3500]
- Months:
- Use
plt.plot()to draw the line chart. - Add chart elements:
- Title: "Monthly Sales Overview"
- X-axis label: "Month"
- Y-axis label: "Sales ($)"
- Grid for readability.
- Display the chart using
plt.show().
Exercise 2: Faker
Use the faker library (https://pypi.org/project/Faker/) to generate synthetic customer data.
Instructions:
- Install the
Fakerlibrary. - Write a Python script to generate 100 fake customers with the following fields:
- Full name
- Phone number
- City
- Date of birth
- Job title
- Company name
- Save the data in a file called
customers.csv.
Exercise 3: PDF Text Extraction
Find a library that helps you read the contents of a PDF file and extract its text.
Instructions:
- Download or prepare a sample PDF file.
- Write a script that:
- Opens the PDF file
- Extracts the text from each page
- Prints the content of each page to the console