Python Advanced
This page provides an introduction to python higher order functions, file, time and multithreading.
Lambda
# defining lambda function
add = lambda x, y: x + y
max = lambda x, y: x if x > y else y
full_name = lambda first_name, last_name: first_name + " " + last_name
# calling lambda function
print(add(1, 2))
# o/p: 3
print(max(5, 6))
# o/p: 6
print(full_name("Spongbob", "Squarepants"))
# o/p: Spongbob Squarepants
Map
def c_to_f(temp): return (temp * 9/5) + 32
celsius_temp = [0.0, 10.0, 20.0, 30.0, 40.0, 50.0]
fahrenheit_temp = list(map(c_to_f, celsius_temp))
print(fahrenheit_temp)
# o/p: 32.0, 50.0, 68.0, 86.0, 104.0, 122.0]
Filter
def is_passing(grade): return grade >= 60
grades = [91, 32, 83, 44, 75, 56, 67]
passing_grades = list(filter(is_passing, grades))
print(passing_grades)
# o/p: [91, 83, 75, 67]
Reduce
def add(x, y): return x + y
from functools import reduce
prices = [11, 52, 67, 100]
total = reduce(add, prices)
print(total)
# o/p: 230
File Detection
import os
file_path = "test.txt"
if os.path.exists(file_path):
print(f"File exists")
if os.path.isfile(file_path):
print("That is a file")
elif os.path.isdir(file_path):
print("That is a directory")
else:
print(f"File doesn't exists")
Write File
txt_data = "I like pizza!"
file_path = "output.txt"
with open(file_path, "w") as file:
file.write(txt_data)
print(f"txt file {file_path} was created")
info
Different modes for file operations
- "x" write the file if it doesn't exists.
- "a" append
- "w" overwrite.
- "r" read
Read File
file_path = "input.txt"
try:
with open(file_path, "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("That file was not found")
Time
import time
start_time = time.perf_counter()
for i in range(10000):
pass
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Elapsed Time {elapsed_time:.6f}")
Date & Time
import datetime
date = datetime.date(2025, 1, 2)
today = datetime.date.today()
print(date)
# o/p: 2025-01-02
print(today)
# o/p: 2024-10-28
time = datetime.time(12, 30, 0)
now = datetime.datetime.now()
now_formatted = now.strftime("%m-%d-%y %H:%M:%S")
print(time)
# o/p: 12:30:00
print(now)
# o/p: 2024-10-28 14:17:09.377378
print(now_formatted)
# o/p: 10-28-24 14:17:44
target_datetime = datetime.datetime(2030, 1, 2, 12, 30, 1)
current_datetime = datetime.datetime.now()
if target_datetime < current_datetime:
print("Target date has passed")
else:
print("Target date has not passed")
# o/p: Target date has not passed
Multithreading
import threading
import time
def walk_dog(name):
time.sleep(8)
print(f"You finish walking the {name}")
def take_out_trash():
time.sleep(4)
print("You took out the trash")
def get_mail():
time.sleep(2)
print("You got the mail")
task_1 = threading.Thread(target=walk_dog, args=("Scooby", ))
task_1.start()
task_2 = threading.Thread(target=take_out_trash)
task_2.start()
task_3 = threading.Thread(target=get_mail)
task_3.start()
task_1.join()
task_2.join()
task_3.join()
print("All tasks are completed")
# o/p:
# You got the mail
# You took out the trash
# You finish walking the Scooby
# All tasks are completed
API Request
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
if response.status_code == 200:
pokemon_data = response.json()
return pokemon_data
else:
print(f"Failed to retrieved data {response.status_code}")
pokemon_info = get_pokemon_info("pikachu")
if pokemon_info:
print(f"Name: {pokemon_info['name'].capitalize()}")
Setup Python Project
Click Here to see Python Project in github. Below are the steps to create python project template:
# create a directory
mkdir python-project-template && cd python-project-template
# create virtual environment for isolation
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate
# create project structure
mkdir src tests
# make directory src & tests as a package by creating __init__.py
touch src/__init__.py
touch tests/__init__.py
# create source directory with hello world
echo "def hello_world():
return 'Hello, World!'" > src/hello.py
# create test directory with sample test
echo "from src.hello import hello_world
def test_hello_world():
assert hello_world() == 'Hello, World!'" > tests/test_hello_world.py
# create requirements.txt
pip3 freeze > requirements.txt
# create dev requirements
echo "pytest\npytest-cov\ntox\nblack\nisort\nflake8\npylint\nmypy" > requirements-dev.txt
# install dev requirements.txt and requirements-dev.txt
pip3 install -r requirements.txt -r requirements-dev.txt
# add .gitignore file
echo "venv/*\n.tox/*\n__pycache__/*" > .gitignore
We will be using tox for testing, create tox.ini in project root directory with below content:
# Tox configuration file to run tests and formatting checks.
[tox]
# List of environments to be tested. These are the Python versions to be used.
envlist = py38, py39, py310
[testenv]
setenv =
PYTHONDONTWRITEBYTECODE=1
# This is the default environment.
# It runs commands for each Python version specified in the `envlist`.
commands =
# Run tests using pytest
pytest
# Check if the code follows Black's code style without modifying it.
black . --include "/(src|tests)/.*\.py"
# Check if the code follows isort's import order without modifying it.
isort src tests
# Check for PEP8 violations and other code style issues using flake8.
flake8 src tests
# Run pylint for static code analysis, disabling certain checks.
pylint --disable=C0114,C0116,C0115 --ignore=__init__.py src tests
[testenv:py38]
deps =
-rrequirements-dev.txt
[testenv:py39]
deps =
-rrequirements-dev.txt
[testenv:py310]
deps =
-rrequirements-dev.txt
allowlist_externals =
black
To install dependencies, run test cases, and apply formatting, run:
tox
# o/p:
# ...
# py38: OK (4.57=setup[0.08]+cmd[0.64,0.38,0.39,1.69,1.39] seconds)
# py39: OK (3.23=setup[0.03]+cmd[0.36,0.31,0.21,0.83,1.50] seconds)
# py310: OK (3.40=setup[0.03]+cmd[0.39,0.47,0.27,0.82,1.41] seconds)
# congratulations :) (11.27 seconds)
To run specific environment run:
tox -e py38
# o/p:
# ...
# py38: commands[1]> black . --include '/(src|tests)/.*\.py'
# All done! ✨ 🍰 ✨
# 4 files left unchanged.
# py38: commands[2]> isort src tests
# py38: commands[3]> flake8 src tests
# py38: commands[4]> pylint --disable=C0114,C0116,C0115 --ignore=__init__.py src tests
# py38: OK (3.47=setup[0.06]+cmd[0.48,0.31,0.26,0.91,1.44] seconds)
# congratulations :) (3.55 seconds)
Lastly create an empty repo and github and push the changes to github repo.