Posts

Showing posts from June, 2025

Mastering Python's decimal Module 💱

Image
Mastering Python's decimal Module 💱 The decimal module enables precise decimal arithmetic without floating-point inaccuracies, essential for financial, scientific, and precise numerical applications. 1. Basic Usage and Creating `Decimal` Objects from decimal import Decimal a = Decimal('0.1') b = Decimal('0.2') print(a + b) # 0.3 (accurate result, unlike float) 2. Rounding and Precision with `getcontext` from decimal import Decimal, getcontext, ROUND_HALF_UP getcontext().prec = 5 # Set total precision to 5 digits getcontext().rounding = ROUND_HALF_UP res = Decimal('1.23456') + Decimal('2.34567') print(res) # 3.5802 (applied precision and rounding) 3. Financial Calculations and Monetary Representation from decimal import Decimal price = Decimal('19.99') quantity = Decimal('3') total = price * quantity print(f"Total amount: {total}") # Total amount: 59.97 4. Comparisons and Precise Division from de...

Python unittest Module: Writing Automated Unit Tests ✅

Image
Python unittest Module: Writing Automated Unit Tests ✅ The unittest module is Python's built-in unit testing framework, essential for verifying the correctness of your code automatically. 1. Writing Simple Function Tests # calc.py def add(a, b): return a + b # test_calc.py import unittest from calc import add class TestCalc(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) self.assertEqual(add(-1, 1), 0) if __name__ == '__main__': unittest.main() 2. Using `setUp()` and `tearDown()` for Common Tasks # test_list.py import unittest class TestList(unittest.TestCase): def setUp(self): self.lst = [1, 2, 3] def tearDown(self): self.lst.clear() def test_append(self): self.lst.append(4) self.assertIn(4, self.lst) def test_pop(self): value = self.lst.pop() self.assertEqual(value, 3) if __name__ == '__main__': unittest.main() 3. Testing ...

Python subprocess Module Explained 🧩

Image
Python subprocess Module Explained 🧩 The subprocess module allows Python scripts to run external commands, scripts, or programs, capturing their output and managing their execution easily and efficiently. 1. Basic Execution with `subprocess.run()` import subprocess result = subprocess.run(['echo', 'Hello World'], capture_output=True, text=True) print(result.stdout) # Hello World 2. Checking Errors and Return Codes import subprocess res = subprocess.run(['ls', 'non_existent_folder'], capture_output=True, text=True) if res.returncode != 0: print("Error:", res.stderr) else: print(res.stdout) 3. Sending Input and Reading Output import subprocess p = subprocess.run(['grep', 'hello'], input='hello world\nhi python', capture_output=True, text=True) print(p.stdout) # hello world 4. Asynchronous Execution with `Popen` import subprocess p = subprocess.Popen(['ping', '-c', '3...

Python's shutil Module Explained 🧰

Image
Python's shutil Module Explained 🧰 The shutil module provides a high-level interface for performing various file and directory operations, such as copying, moving, archiving, and checking disk usage. 1. Copying and Moving Files import shutil # Copy a single file shutil.copy('source.txt', 'dest.txt') # Copy file with metadata shutil.copy2('source.txt', 'backup/source_backup.txt') # Move or rename files shutil.move('old.txt', 'new_folder/renamed.txt') 2. Copying and Removing Directories import shutil # Copy entire directory shutil.copytree('src_folder', 'dst_folder') # Remove entire directory shutil.rmtree('dst_folder') 3. Checking Disk Usage import shutil total, used, free = shutil.disk_usage('/') print(f"Total: {total // (2**30)}GB, Used: {used // (2**30)}GB, Free: {free // (2**30)}GB") 4. Creating and Extracting Archives import shutil # Create zip archive shutil.m...

Getting Started with Python's asyncio ⚡

Image
Getting Started with Python's asyncio ⚡ asyncio is Python’s powerful library for asynchronous programming, enabling efficient handling of network I/O, file operations, and timing-related tasks. 1. Writing Basic Async Functions import asyncio async def say_hello(): print("Hello") await asyncio.sleep(1) print("World") asyncio.run(say_hello()) 2. Executing Multiple Tasks Concurrently import asyncio async def worker(name, delay): await asyncio.sleep(delay) print(f"{name} completed after {delay} seconds") async def main(): tasks = [ worker("Task A", 1), worker("Task B", 2), worker("Task C", 1.5) ] await asyncio.gather(*tasks) asyncio.run(main()) 3. Network I/O Example with aiohttp import asyncio import aiohttp async def fetch(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: print(url, ...

Mastering Python's random Module 🎲

Image
Mastering Python's random Module 🎲 The random module provides versatile tools for generating random numbers, shuffling sequences, sampling, and more. It's widely used for testing, simulations, and probabilistic operations. 1. Generating Random Numbers: uniform, randint, random import random print(random.random()) # float between 0.0 and 1.0 print(random.uniform(10, 20)) # float between 10 and 20 print(random.randint(1, 6)) # integer between 1 and 6 2. Fixing the Seed for Reproducibility import random random.seed(123) print([random.randint(1, 100) for _ in range(5)]) # same results every time 3. Shuffling and Sampling Lists import random arr = list(range(1, 11)) random.shuffle(arr) # shuffle list randomly print(arr) sample = random.sample(arr, 3) # select 3 unique elements print(sample) 4. Weighted and Simple Random Choices import random choices = ['Rock', 'Paper', 'Scissors'] print(random.choice(ch...

Mastering Python's JSON Module 📝

Image
Mastering Python's JSON Module 📝 The json module in Python is essential for converting JSON data to Python objects and vice versa, handling formatting, and managing JSON files seamlessly. 1. JSON String ↔ Python Object import json data = '{"name": "John", "age": 30, "languages": ["Python", "JavaScript"]}' obj = json.loads(data) print(obj, type(obj)) # {'name': 'John', 'age': 30, 'languages': ['Python', 'JavaScript']} s = json.dumps(obj) print(s, type(s)) # String 2. Pretty Printing with Indentation import json obj = {"name": "Jane", "age": 25, "city": "New York"} pretty = json.dumps(obj, indent=4, ensure_ascii=False) print(pretty) # { # "name": "Jane", # "age": 25, # "city": "New York" # } 3. Reading and Writing JSON Files import json...

Python CSV Module: Reading and Writing CSV Files 📄

Image
Python CSV Module: Reading and Writing CSV Files 📄 The csv module simplifies working with comma-separated values files. Let's explore its basic and advanced features with clear examples. 1. Reading Simple CSV Files import csv with open('data.csv', newline='', encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row) # ['Name', 'Age', 'Country'] 2. Writing to a CSV File import csv data = [ ['Name', 'Score', 'Remark'], ['Alice', '85', 'Pass'], ['Bob', '92', 'Excellent'] ] with open('results.csv', 'w', newline='', encoding='utf-8') as csvfile: writer = csv.writer(csvfile) writer.writerows(data) 3. Using DictReader for Key-Value Reading import csv with open('data.csv', newline='', encoding='utf-8') as csvfile: reader =...

Python's pathlib Module 📁

Image
Python's pathlib Module 📁 The pathlib module enables handling filesystem paths in an object-oriented manner, providing intuitive and OS-independent path manipulations. 1. Basic Usage and Creating a Path Object from pathlib import Path p = Path('my_folder') / 'subfolder' / 'example.txt' print(p) # my_folder/subfolder/example.txt print(p.exists()) # False (checks existence) 2. Creating Directories and Reading/Writing Files folder = Path('logs') folder.mkdir(exist_ok=True) file = folder / 'app.log' file.write_text("Application log\n", encoding='utf-8') print(file.read_text(encoding='utf-8')) 3. Getting File Information print(file.name) # app.log print(file.stem) # app print(file.suffix) # .log print(file.parent) # logs print(file.stat().st_size, "bytes") 4. Iterating Over Directory Contents for child in folder.iterdir(): print(child.name, "-", "...

Mastering Python's contextlib Module 🧰

Image
Mastering Python's contextlib Module 🧰 The contextlib module provides helpful utilities to efficiently manage resources with Python's context managers, making your code cleaner and safer. 1. @contextmanager : Simple Context Managers from contextlib import contextmanager @contextmanager def open_file(name, mode): f = open(name, mode) try: yield f finally: f.close() with open_file('test.txt', 'w') as f: f.write('Hello, world!') 2. closing : Manage Objects that Need Closing from contextlib import closing from urllib.request import urlopen with closing(urlopen('http://example.com')) as page: for line in page: print(line) 3. suppress : Ignore Specific Exceptions from contextlib import suppress import os with suppress(FileNotFoundError): os.remove('somefile.tmp') 4. redirect_stdout : Redirect Output from contextlib import redirect_stdout with open('output.txt', ...

Mastering Python's functools Module 🧰

Image
Mastering Python's functools Module 🧰 The functools module provides powerful tools for functional programming, helping you write efficient and reusable Python code. Let’s dive into its key functionalities with clear examples. 1. lru_cache : Speed Up Functions by Caching Results from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(30)) # Quick result due to caching 2. partial : Fix Arguments of a Function from functools import partial def multiply(x, y): return x * y double = partial(multiply, 2) print(double(5)) # 10 3. cmp_to_key : Custom Sorting with a Comparison Function from functools import cmp_to_key def compare(a, b): return b - a # Descending order numbers = [5, 2, 9, 1] sorted_numbers = sorted(numbers, key=cmp_to_key(compare)) print(sorted_numbers) # [9, 5, 2, 1] 4. wraps : Preserve Original Metadata in Decorators from f...