Day 334: cleaning up automatically (Contextlib) 🔒 creating custom "with" statements We all use with open(...) to handle files. It’s great because it automatically closes the file even if the code crashes. This is called a Context Manager. But did you know you can build your own using contextlib? I use this for database connections. I want to ensure the connection closes cleanly, no matter what happens inside the logic block. from contextlib import contextmanager @contextmanager def file_opener(filename): print("Opening file...") f = open(filename, 'w') yield f print("Closing file automatically!") f.close() with file_opener('test.txt') as f: f.write("Hello Custom Context!") Why it matters: It keeps your resource management code clean and prevents memory leaks. #Python #CleanCode #AdvancedPython #Backend
Custom Contextlib for Clean Resource Management
More Relevant Posts
-
Day 309: Python pathlib — Clean, Modern File Paths 📂 Path Manipulation with pathlib Before pathlib, file paths were messy strings. Now they’re objects, and that changes everything. pathlib makes file handling readable, safer, and cross-platform. 👉 Example: from pathlib import Path path = Path('/home/user/docs') print(path.exists()) new_dir = path / 'new_folder' new_dir.mkdir(parents=True, exist_ok=True) for file in path.iterdir(): print(file) 🧠 Why pathlib feels better: •No string concatenation •No OS-specific separators •Clean, expressive syntax 💡 Use pathlib when: •Working with files or directories •Writing cross-platform code •You want readable, maintainable scripts 🎯 Challenge: Search for all .py files recursively in a directory using pathlib. #PythonPathlib #FileHandling #CleanCode
To view or add a comment, sign in
-
Stop blocking your Python API with synchronous DB calls. I see this pattern a lot: A developer moves from Flask to FastAPI for "speed," but keeps using the standard synchronous session.query() in their database layer. Result? You have a Ferrari engine (FastAPI) stuck in first gear (Blocking I/O). I just wrote a guide on how to build a fully Async backend using the modern stack: ⚡ FastAPI (The Interface) 🗄️ SQLAlchemy 2.0 (The ORM - using the new 2.0 syntax) 🔄 Aiosqlite/AsyncPG (The Non-blocking Drivers) The shift from query() to await session.execute(select(...)) is small in code, but massive in performance under load. I included the full setup code, dependency injection patterns, and Pydantic V2 schemas in the article. Read the full guide here: [https://lnkd.in/gnT39HMP] #Python #FastAPI #BackendDevelopment #SQLAlchemy #SystemDesign
To view or add a comment, sign in
-
-
Solved LeetCode 944 – Delete Columns to Make Sorted 🧠📊 This problem looks simple at first, but it’s a great reminder that clear thinking beats complex logic. 🔍 Problem in short: - You’re given multiple strings of equal length. Imagine them stacked one below another, forming a grid. Your task is to delete columns that are NOT lexicographically sorted from top to bottom and return how many such columns exist. 🧠 How I approached it: 1️⃣ First, I visualized the strings as a table where: - Each row is a string - Each column contains characters from all strings at that position 2️⃣ Then, I checked each column independently: - Start from the top row - Compare every character with the one directly below it 3️⃣ If at any point: - The upper character is greater than the one below → That column is not sorted 4️⃣ The moment a column fails this condition: - I mark it for deletion - Move on to the next column (no need to check further for that one) 5️⃣ Finally, I count how many columns were marked for deletion. ✨ Key takeaway - You don’t always need advanced data structures. - Sometimes, a simple comparison + clean iteration is all it takes. #LeetCode #DSA #ProblemSolving #Python #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟭𝟮/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 11. Container With Most Water 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that, together with the x-axis, form a container that can store the maximum amount of water. Return the maximum amount of water the container can store. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Initialized a variable area to store the maximum water. Used two pointers, start at the beginning of the array and end at the end of the array. Iterated using a while loop while start < end. For each pair of pointers, calculated the area using: • Width = end - start • Height = minimum of height[start] and height[end] Updated the maximum area accordingly. If the height at start was smaller, incremented start; otherwise, decremented end. This ensured all potential maximum-area combinations were efficiently explored. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), single traversal • Space Complexity: O(1), constant extra space 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: The two-pointer technique helps reduce a brute-force O(n²) solution to an efficient linear-time approach. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/gjMe4zgC #Day12of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
When working in insight and data everyone ask to get a dashboard that turns raw data into actionable insight. No one says "Make it look beautiful"... I spent 30 minutes "vibe coding" with Claude Code to see how fast I could spin up a dashboard with my preferred stack. The result is a complete pipeline: Python script to simulate the data, DuckDB for storage, FastAPI to expose it, and a Svelte frontend for full flexibility. Repo with code and instructions to spin it up is here: https://lnkd.in/ewsKyV9h
To view or add a comment, sign in
-
Stop hardcoding dependencies in your Fast API apps. Dependency Injection (DI) isn’t just a design pattern in Fast API, it’s a superpower. By using the Depends keyword, you move the complexity of database sessions, authentication, and configurations out of your logic and into a managed "container." Why this matters: ✅ Loose Coupling: Swap production databases for mocks in one line. ✅ DRY Code: Define a security dependency once, use it across 50 endpoints. ✅ Clean Logic: Your route functions focus on business logic, not setup. If you’re building production-grade Python APIs, mastering the DI system is the single best way to ensure your code stays maintainable as it scales. Check out the flow below to see how FastAPI handles the heavy lifting before your code even executes. 👇 #FastAPI #Python #SoftwareArchitecture #CleanCode #BackendDevelopment
To view or add a comment, sign in
-
-
Reusing code with default mutable arguments? You're setting yourself up for a nasty surprise. It's 2026, and this one still catches people. We had a 'convenience' function for logging events, complete with a default list of tags. Everybody loved it; made their calls look clean. Then we started seeing production logs with completely unrelated tags. Debugging this felt like chasing ghosts through a maze of microservices and shared libraries. Turns out, that shared `tags=[]` default was getting mutated. Every time someone called the function without providing their own tags, they were just appending to the *same list instance* from previous calls. Request A's tags showed up in Request B's logs. ❌ **The Trap:** `def log_event(message, tags=[]):` ✅ **The Reality:** `def log_event(message, tags=None):` then `tags = tags if tags is not None else []` Hidden state in seemingly stateless functions will burn you every time. Anyone else debugged this exact mess more times than they care to admit? #ProductionLogs #Python #FunctionsAndReusability #SoftwareEngineering
To view or add a comment, sign in
-
𝗗𝗮𝘆 𝟭𝟭/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 392. Is Subsequence 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Easy 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given two strings s and t, return true if s is a subsequence of t; otherwise, return false. A subsequence is formed by deleting some (or none) characters from the original string without changing the relative order of the remaining characters. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Initialized a pointer k to track the current index in string s. Iterated through string t using a for loop. For each character in t, checked whether it matches the current character in s using the charAt function. If a match was found, incremented k. After completing the traversal, if k equals the length of s, it means all characters of s were found in t in the correct order, so return true; otherwise, return false. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), traversal of string t • Space Complexity: O(1), constant extra space 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: The two-pointer technique provides a simple and efficient way to verify subsequence relationships. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/gCssiwQD #Day11of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟵/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 443. String Compression 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: • If the group length is 1, append the character to s. • Otherwise, append the character followed by the group length. The compressed string should not be returned separately but must be stored directly in the input array chars. Group lengths greater than or equal to 10 should be split into multiple characters. After modifying the array, return the new length of chars. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Initialize a string variable s and a counter variable count with an initial value of 1. Iterate through the array starting from index 1. If the current character is the same as the previous one, incremented count. Otherwise, append the previous character to s, and if count > 1, append the count as well. After completing the loop, append the last character and its count. Finally, iterat through the chars array to overwrite it with the characters from s and return the length of s. 𝗔𝗹𝘁𝗲𝗿𝗻𝗮𝘁𝗶𝘃𝗲 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Initialize two pointers: read and write, both set to 0. Traverse the array using a while loop. Store chars[read] in a character variable current. Use an inner while loop to count consecutive occurrences of current. Update the chars array in-place by writing the character and its count (if greater than 1). The outer loop handled unique characters, while the inner loop calculated their frequencies. Return the write pointer as it represents the new length of the compressed array. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), due to single traversal of the array • Space Complexity: O(1), since only constant extra space is utilised. 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Using the two-pointer technique enables efficient in-place string compression while maintaining optimal time and space complexity. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/g4q7uhbw #Day9of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development