🐒 Monkey Patching — Powerful but Risky Monkey patching means changing or extending code at runtime without modifying its original source. Dynamic languages like Python allow this because classes and functions are mutable while the program is running. Example:- class Calculator: def add(self, a, b): return a + b Now we change its behaviour without touching the class: def new_add(self, a, b): return a + b + 10 Calculator.add = new_add calc = Calculator() print(calc.add(2, 3)) # 15 That’s monkey patching in action. ✅ Pros 1. Quickly fix or override behaviour in third-party libraries 2. Very useful for mocking dependencies during testing 3. No need to change or redeploy original source code 4. Helpful in legacy systems where changes are restricted ❌ Cons 1. Makes code harder to read and reason about 2. Behaviour changes are implicit and not obvious 3. Can break unexpectedly after library upgrades 4. Debugging becomes more complex Rule of thumb: Use monkey patching sparingly, document it clearly, and prefer cleaner patterns like dependency injection when possible. Have you ever used monkey patching in real projects? 👇 #Python #SoftwareEngineering #ProgrammingConcepts #CleanCode #BackendDevelopment #Testing #PythonTips #DeveloperLife #CodeQuality #TechLearning
Monkey Patching in Python: Pros and Cons
More Relevant Posts
-
Today’s focus was a LeetCode Easy problem that tests real logical discipline, not tricks. 🔹 LeetCode #9 – Palindrome Number At first glance, this looks trivial. It isn’t. The task is simple: Check whether a number reads the same forward and backward. What actually matters while solving it: Negative numbers must be rejected immediately The original value must be preserved before mutation Digits must be extracted and rebuilt correctly Loop termination has to be precise The approach I used: Reverse the number digit by digit using modulo and integer division Compare the reversed value with the original number The logic is straightforward, but any missed condition silently breaks the solution. Key takeaway: Easy problems don’t fail because of complexity. They fail because of careless edge-case handling. Alongside this, I’m also solving smaller logic-building problems focused on: Conditional branching Boundary validation Correct ordering of conditions These reinforce the same thinking from a different angle. 🔗 GitHub Repository (all solutions): 👉https://lnkd.in/d5J4MA8q #LeetCode #Python #ProblemSolving #LogicBuilding #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
⚡ Tackling if-else statements be like… We’ve all been there: one more condition, then another, and just one more edge case. Before you know it, your code works… but nobody wants to touch it. 😅 The problem isn’t that nested conditionals work. The problem is what happens six months later when you need to change them. Here are some alternatives I reach for: → Early returns instead of deep nesting → Guard clauses to fail fast → Lookup tables instead of long if-else chains → Strategy pattern for complex logic → Well-named functions for clarity The best refactoring moment? When you catch yourself adding the third level of nesting. 🚨 What’s your rule of thumb for refactoring nested conditionals? #SoftwareEngineering #Programming #CleanCode #DevLife #Python #Java #LinkedIn
To view or add a comment, sign in
-
-
Step 3: CI (Build Gates That Stop Bad Deploys) I wired GitHub Actions CI to run on push/PR. Pipeline did: Checkout Python compile/syntax gate Docker build (and later publish) What I practiced explaining: Where failures stop deployment (CI is a gate) Why “main protected” matters conceptually (only merge what’s verified) Gotcha: Workflow ran twice (push + pull_request). Learned why and when to scope triggers. Next: CD.
To view or add a comment, sign in
-
built a tui (terminal ui) in last two days, claude code wrote all python code and documentation: launch a list screen w 4 filters and search function, click to drill down to a detail screen with summary, status and a sublist modules, the sublist can click to open a full report detail screen, key and mouse based ui flow, with data coming from a middle tier cgi server which connects to backend spark sql tables. there are local cache to speedup, proxy authentication from ui host to middleware, 4 tables w joining to support the ui, finally everything wrapped in a docker container sandbox to download… claude code is addictive…i want to try opencode and the free llms, are they good?
To view or add a comment, sign in
-
Day 13: From Python-Shell Chaos to API Success: A Debugging Saga Just spent 4 hours debugging what should have been a 10-minute setup. Here's what happened: The Problem: My FastAPI app kept crashing with cryptic errors. Uvicorn said "SyntaxError" but the code looked perfect. Upon Investigation: Virtual environment? Check. Dependencies installed? Check. File structure correct? Check. But still... "unterminated string literal" errors! The Culprit: My app/__init__.py file had PowerShell syntax mixed with Python! Somehow @' | Out-File commands ended up in a .py file. The Big Lesson : Language boundaries matter - PowerShell ≠ Python Cache is sneaky - .pyc files can haunt you Simple problems have simple solutions - sometimes it's just one corrupted file Persistence pays - don't give up when the error messages don't make sense The Fix: bash # The magical fix was simpler than expected rm -rf __pycache__ # Clear Python cache rm app/__init__.py # Delete corrupted file # Create fresh, clean file echo "# Python package init" > app/__init__.py The Result: API running perfectly, analytics dashboard live, and PowerShell utilities working seamlessly! Key Takeaways: Always check file encodings (UTF-8 BOM can break Python) Clear cache when things don't make sense One corrupted file can break everything The solution is often simpler than the problem appears #Debugging #Python #FastAPI #BackendDevelopment #APIDevelopment #Programming #Coding #SoftwareEngineering #TechStruggles #DeveloperLife #LearningFromFailure #CodeQuality #TechSolutions
To view or add a comment, sign in
-
New portfolio project: API Test Automation with Pytest + CI/CD (GitHub Actions) In modern microservices architectures, APIs are the main contracts between services. A small breaking change (status code, field removal, schema mismatch) can easily cascade and break multiple dependent services. In this project, I implemented an automated API test suite using Python + Pytest, validating a public REST API (Rick and Morty) with focus on: ✅ Contract and payload validation for GET /character/{id} ✅ Query parameter coverage for GET /character?name=... ✅ Negative scenarios (invalid IDs → 404 + error payload) ✅ Lightweight performance checks (response time thresholds) The suite runs automatically on every push via GitHub Actions CI, generating JUnit test reports and coverage artifacts. This kind of validation is essential to ensure stability, confidence in deployments, and fast feedback in distributed systems. 🔗 Repository: https://lnkd.in/eQBudsXM
To view or add a comment, sign in
-
🚀 LeetCode 904 – Fruit Into Baskets | Sliding Window Mastery 🍎 Today’s problem looked simple at first… but it’s a perfect test of thinking in windows, not loops. 🧠 The Challenge You’re walking through an orchard, picking fruits 🍓🍎 You can carry only 2 types of fruits, but you want to collect as many as possible in a row. Sounds easy? The trick is knowing when to expand and when to shrink your window. ✨ Key Insight (Aha Moment!) Instead of restarting every time the rule breaks: 👉 Maintain a sliding window that always contains at most 2 fruit types When a 3rd type appears: 🔹 Shrink the window from the left 🔹 Remove fruits until only 2 types remain 🔹 Keep tracking the maximum window size This converts a brute-force problem into an O(n) optimal solution ⚡ 📌 What this problem really teaches 🔹 How to manage frequency with a hashmap 🔹 When and why to shrink a window 🔹 How “at most K distinct elements” problems work 🔹 Real-world thinking applied to DSA 💡 Pattern Recognition Tip If you see: ➡️ Longest subarray ➡️ At most 2 / K distinct elements 🎯 Think Sliding Window + Frequency Map 🔥 Problems like this build intuition, not just code. Each sliding window problem makes the next one feel easier. #LeetCode #DSA #SlidingWindow #ProblemSolving #CodingJourney #Java #Python #TechLearning
To view or add a comment, sign in
-
-
Maintaining an open source project with pure Python for maximized portability, I created a tool to filter dependencies for native/compiled code. This client-side utility includes tree visualization, binary detection, deep scan, and aims at locating potential issues for WASM environments. Prototype with Claude/Gemini, iterations for resolving edge cases, and contributions for improving dependency resolution are welcome. Visualize Python dependencies and subprocess calls in a browser: https://lnkd.in/e7Cv8xaB source,#webassembly,#dependency visualization
To view or add a comment, sign in
-
Yesterday, I built pipscope out of pure frustration. I was debugging a dependency mismatch and found myself stuck in the same loop again and again pip show, pip list | grep <x>, scrolling, re-running commands, losing context. What I really wanted was an interactive pip list, where I could keep searching freely, click into a package, see pip show-style details, check dependencies, and understand what depends on what, without starting over every time. That tool didn’t exist (at least not the way I wanted), so I built it. pipscope is a terminal UI to explore installed Python packages. It is designed to make dependency debugging feel effortless instead of exhausting. If you’ve ever been annoyed by Python dependency chaos, this might help. Give it a try: pip install pipscope
To view or add a comment, sign in
-
More from this author
Explore related topics
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