KEMBAR78
Advanced Topics | PDF | Modular Programming | Software Engineering
0% found this document useful (0 votes)
5 views23 pages

Advanced Topics

The document explains the concepts of modules and packages in Python, highlighting their structure, usage, and benefits such as reusability and clean code. It also introduces APIs, detailing their purpose, types (like RESTful APIs), and how to make requests and build your own API using Flask. Best practices for naming and organizing modules and packages are also provided.

Uploaded by

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

Advanced Topics

The document explains the concepts of modules and packages in Python, highlighting their structure, usage, and benefits such as reusability and clean code. It also introduces APIs, detailing their purpose, types (like RESTful APIs), and how to make requests and build your own API using Flask. Best practices for naming and organizing modules and packages are also provided.

Uploaded by

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

PROGRAM ORGANISATION

USING MODULES AND PACKAGES

By
Dr. Julius Olaniyan
Module

• A module is a single Python file (.py) that


contains code — functions, classes, or
variables — that can be reused in other
Python files.
Module - Example
• # file: calculator.py
def add(x, y):
return x + y

def subtract(x, y):


return x - y
Module - Example
• You can use the calculator.py in another
Python file:

import calculator
print(calculator.add(5, 3)) # Output: 8
print(calculator.subtract(5, 3)) # Output: 2
Package
• A package is a folder that contains multiple
modules and a special file named __init__.py
(can be empty). The __init__.py file tells Python
this directory is a package.
• Structure:
• math_tools/
• │
• ├── __init__.py
• ├── basic.py
• └── advanced.py
Modules Usage in another file
• basic.py from math_tools import basic,
def add(x, y): advanced
return x + y
print(basic.add(2, 3)) #
• advanced.py Output: 5
def power(x, y): print(advanced.power(2, 3))
return x ** y # Output: 8
Why Use Modules and Packages?

• 🔁 Reusability – Write once, use many times.


• 🧼 Clean Code – Keeps files short and readable.
• 🧱 Modularity – Each file/folder handles a specific
functionality.
• 🧪 Easier Testing – Test individual components separately.
Creating and Using Modules & Packages –
Step by Step
• STEP 1: Create a Simple Module
• Create a file called greetings.py:
# greetings.py
def say_hello(name):
return f"Hello, {name}!"
– Use it in main.py:
# main.py
import greetings
print(greetings.say_hello("Julius")) # Output: Hello,
Julius!
Creating and Using Modules & Packages –
Step by Step
• STEP 2: Create a Package
• Create a folder: my_package/
• Inside my_package/, add:
– my_package/
– ├── __init__.py
– ├── greetings.py
– └── math_ops.py
Creating and Using Modules & Packages –
Step by Step
Modules main.py
• greetings.py from my_package import greetings, math_ops
def say_hi(name):
return f"Hi, {name}!" print(greetings.say_hi("Ada"))# Output: Hi, Ada!
print(math_ops.multiply(2, 5)) # Output: 10
• math_ops.py
def multiply(x, y):
return x * y
STEP 3: Using __init__.py to Control Imports
• Edit __init__.py in my_package/
from .greetings import say_hi
from .math_ops import multiply

Now in main.py:
from my_package import say_hi, multiply

print(say_hi("Julius")) # Output: Hi, Julius!


print(multiply(3, 4)) # Output: 12
Advanced: Relative vs Absolute Imports

Absolute Import:
from my_package.greetings import say_hi

Relative Import (inside a package):


from .greetings import say_hi # Dot means current package

Best Practices
✅ Name modules and packages with lowercase letters and underscores.
✅ Keep modules focused on one topic (e.g., auth.py, utils.py, database.py).
✅ Avoid circular imports (A imports B, B imports A).
✅ Use __init__.py to expose only useful functions.
API
• What is an API?
– API stands for Application Programming
Interface.
• Definition:
– An API is a set of rules and protocols that allows
one software application to communicate with
another.
API ANALOGY
• Think of an API like a waiter in a restaurant.

You (user) ask the waiter (API) for food.


The waiter takes the order to the kitchen (server).
The kitchen prepares the food (data).
The waiter brings it back to you (response).
✅ Why Use APIs?

• 📡 Access services (e.g., weather, maps,


Twitter)
• ♻️Reuse functionality from other apps
• 🔒 Secure data access with authentication
• ⚡ Speed up development (no need to reinvent
the wheel)
Types of APIs
RESTful API (Most Common Type)

• REST = Representational State Transfer


• 🔹 Characteristics:
– Uses HTTP methods:
• GET: Retrieve data
• POST: Create new data
• PUT: Update existing data
• DELETE: Delete data
– Returns data in JSON or XML
– Stateless (no client context stored on the server)
Making API Requests
• Step 1: Install requests
• pip install requests
• Step 2: Make a GET Request
• import requests

• response = requests.get("https://api.github.com")
• print(response.status_code) # 200 means OK
• print(response.json()) # Returns JSON data
Get User Data from GitHub API
import requests

url = "https://api.github.com/users/octocat"
response = requests.get(url)
data = response.json()

print(f"Name: {data['name']}")
print(f"Public Repos: {data['public_repos']}")
Authentication with APIs
• Some APIs require API keys (like passwords).
headers = {
"Authorization": "Bearer YOUR_API_KEY"
}

response = requests.get("https://api.example.com/data",
headers=headers)
Building Your Own API
• pip install flask
# simple_api.py
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/hello', methods=['GET'])
def hello():
return jsonify({"message": "Hello, Julius!"})

if __name__ == '__main__':
app.run()

• Then visit http://127.0.0.1:5000/hello in your browser.


Testing APIs (Postman or Browser)
• Postman/Apidog is a free tool to send API
requests easily.
• You can also use curl in terminal:
• curl https://api.github.com/users/octocat
THANK YOU

You might also like