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
Default Mutable Args in Python Functions: A Hidden Pitfall
More Relevant Posts
-
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
-
Today’s reminder: Logs never lie. Patience always pays. I spent a significant part of the day debugging a production issue where our FastAPI service was crashing on startup. By digging through NGINX configs, Gunicorn logs, and Python stack traces, I eventually found the culprit: a series of small but critical syntax and indentation errors. One missing bracket. One unclosed dictionary. One broken indentation. That was all it took to bring the whole service down. However, step by step, using proper log analysis and systemd journaling, we identified and fixed everything. Key Takeaway: Always run syntax checks and compile validation before deploying. A simple command like: python3 -m compileall ...can save hours of downtime and stress. Production doesn’t fail loudly; it fails precisely. What’s the simplest syntax error that has ever caused you the biggest headache? Let me know in the comments. #DevOps #FastAPI #Python #BackendEngineering #ProductionDebugging
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
-
-
Recently, I was working on a problem that required dynamically constructing a string. My initial implementation was straightforward and functionally correct. At first glance, it seemed perfectly acceptable. However, upon reviewing the logic more carefully, I revisited how Python handles strings internally. Since strings in Python are immutable, each concatenation inside a loop creates a new string object. This means that with every iteration, memory is reallocated and the existing content is copied over. As input size increases, this results in repeated allocations and copying — leading to unnecessary overhead and potential quadratic time complexity. While this may not be noticeable for small inputs, it becomes increasingly inefficient in production environments where code runs frequently or processes large datasets. To optimize the solution, I refactored the implementation to accumulate values in a list and join them at the end. This approach avoids repeated string creation and achieves linear time complexity, improving both performance and memory efficiency. It was a small refactor, but a meaningful one. Moments like this are a good reminder that understanding language internals — even for simple operations — can significantly impact the quality and efficiency of the code we write. #Python3 #Performance #CleanCode #SoftwareEngineering #Optimization
To view or add a comment, sign in
-
-
I replaced 3 Python tools with 1 and my CI pipeline got 10x faster. The tools I dropped: black, isort, flake8. The replacement: Ruff. I've now migrated 7 repositories to Ruff (totaling 800+ Python files) and here's my honest take after 3 months. What's great: - Speed. Ruff lints my entire monorepo in under 2 seconds. The old stack took 20-30 seconds. In CI, that compounds fast across matrix builds. - One config block. Instead of [tool.black], [tool.isort], [tool.flake8] scattered across pyproject.toml, it's just [tool.ruff] and [tool.ruff.lint]. Select the rule codes you want, done. - Auto-fix. Ruff can fix most import sorting and unused import issues on save. I have it wired as a post-tool hook in my editor — every file save auto-formats. What's not perfect: - Rule parity isn't 100%. A few flake8 plugins I relied on (like flake8-bugbear's B950 line length) don't have exact equivalents. You adapt. - The error messages are sometimes less descriptive than flake8's. When a rule fires that you haven't seen before, you're reading docs more often. - If your team has muscle memory around black's opinionated formatting, Ruff's formatter makes slightly different choices in edge cases. Minor, but it can cause noisy diffs during migration. Bottom line: I'd never go back. The speed alone justifies the switch, and consolidating 3 config sections into 1 removes a real source of drift. If you're still running black + isort + flake8 separately, try `ruff check . --fix` on your repo. You'll feel the difference immediately. Have you switched to Ruff yet? What held you back (or convinced you)? #Python #DevTools #Ruff #DeveloperExperience #CodeQuality
To view or add a comment, sign in
-
AI Web Designer that generates complete HTML websites directly inside a Python notebook and renders them. The demo is built with Mercury and shows how notebooks can go beyond experiments - the AI writes pure HTML, the page is previewed instantly, and the source code is visible side by side. Notebook code https://lnkd.in/dpA45rn9
To view or add a comment, sign in
-
Another subtle Python quirk that silently breaks production… The logs showed empty lists where data should be. No errors. No crashes. Just… silence from a core function. After tracing through permissions, database calls, and network timeouts, I found this: (See screenshot for code snippet) The villain? Iterator exhaustion. zip returns an iterator. The first list comprehension consumed it entirely. The second got nothing. This pattern is everywhere: map, filter, csv.reader, generator expressions — they’re all one-time use. Key Insight for System Design: Treat iterators as streams, not containers. A stream flows once. If you need a container, materialize it: data = list(iterator) It’s a simple rule that prevents insidious bugs. What looks like harmless variable reuse can become a source of Heisenbugs — bugs that vanish when you add debug prints (which also consume the iterator!). Python backend issues that don’t throw errors, but break systems quietly. What’s your most memorable “silent failure” bug? #python #debugging #bestpractices #backend #engineering
To view or add a comment, sign in
-
-
🧠 Python Feature That Makes Error Handling Elegant: contextlib.suppress 💫 No noisy try/except. 💫 No empty except: pass. 💫 Just clean intent ❌ Old Way try: os.remove("temp.txt") except FileNotFoundError: pass Works… but feels messy 😬 ✅ Pythonic Way from contextlib import suppress with suppress(FileNotFoundError): os.remove("temp.txt") Readable. Explicit. Clean. 🧒 Simple Explanation Imagine wearing noise-canceling headphones 🎧 You choose which noise to ignore. Python ignores only that error — nothing else. 💡 Why This Is Powerful ✔ Cleaner error handling ✔ Avoids swallowing real bugs ✔ Very expressive code ✔ Used in production-grade code ⚠️ Important Rule Only suppress errors you truly expect (never hide bugs blindly ❌) 💻 Clean code isn’t about removing errors. 💻 It’s about handling them intentionally 🐍✨ 💻 contextlib.suppress is Python being elegant again. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Do you trust a package released two hours ago in production? Installing updated package versions is essential to benefit from new features and bug fixes. However, freshly released versions can introduce bugs or incompatibilities before the community has time to catch them. uv from Astral's exclude-newer option lets you set a cooldown period to skip packages released within a specified timeframe. To use it, add exclude-newer = "7 days" to pyproject.toml and customize the duration as needed. 📬 Want more production-ready data science tips? Subscribe to my newsletter at https://bit.ly/49sglaM #uv #Python #DevOps #PackageManagement
To view or add a comment, sign in
-
-
[EN] This would have been extremely useful to me when something suddenly changed between versions of PowerPlatform-DataverseClient-Python! It’s a great feature to add during development. Additionally, if you’re working on a Python integration that reads from or writes to Dataverse, I recommend this library (or using the API directly).
Do you trust a package released two hours ago in production? Installing updated package versions is essential to benefit from new features and bug fixes. However, freshly released versions can introduce bugs or incompatibilities before the community has time to catch them. uv from Astral's exclude-newer option lets you set a cooldown period to skip packages released within a specified timeframe. To use it, add exclude-newer = "7 days" to pyproject.toml and customize the duration as needed. 📬 Want more production-ready data science tips? Subscribe to my newsletter at https://bit.ly/49sglaM #uv #Python #DevOps #PackageManagement
To view or add a comment, sign in
-
More from this author
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