I used to copy-paste the same logging block into every function. Then I learned decorators. And deleted 200 lines of code in one afternoon. Here's what changed: **Before:** ```python def get_user(user_id): logger.info(f"Calling get_user with {user_id}") start = time.time() result = db.query(...) logger.info(f"get_user took {time.time() - start:.2f}s") return result ``` Every. Single. Function. 😅 **After:** ```python def log_execution(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) logger.info(f"{func.__name__} took {time.time() - start:.2f}s") return result return wrapper @log_execution def get_user(user_id): return db.query(...) ``` Clean. Reusable. Readable. The 3 decorator patterns I use every week: - `@log_execution` — timing and logging - `@retry(max_attempts=3)` — auto-retry on transient errors - `@cache_result(ttl=300)` — simple in-memory caching The key insight: decorators are just functions that wrap functions. Once that clicks, you stop copy-pasting and start composing. What's your favorite decorator pattern? Drop it in the comments 👇 #Python #BackendDevelopment #SoftwareEngineering #Programming #Django
Artur Keraz’s Post
More Relevant Posts
-
🧠 Python Concept: functools.partial Pre-fill function arguments like a pro 😎 ❌ Without partial def power(base, exp): return base ** exp def square(x): return power(x, 2) def cube(x): return power(x, 3) 👉 Repeating logic 👉 Extra functions ✅ With partial from functools import partial def power(base, exp): return base ** exp square = partial(power, exp=2) cube = partial(power, exp=3) print(square(5)) # 25 print(cube(5)) # 125 🧒 Simple Explanation Think of it like preset settings 🎛️ ➡️ Fix some arguments ➡️ Reuse the function easily 💡 Why This Matters ✔ Reduces duplication ✔ Cleaner code ✔ Functional programming style ✔ Useful in callbacks & configs ⚡ Real-World Use ✨ API parameter presets ✨ Event handlers ✨ Reusable utilities 🐍 Don’t repeat functions 🐍 Pre-configure them #Python #AdvancedPython #CleanCode #SoftwareEngineering #BackendDevelopment #Programming #DeveloperLife
To view or add a comment, sign in
-
-
I was debugging a Django service last week and hit a classic problem memory growing silently across requests, no obvious culprit. The usual suspects (tracemalloc, memory_profiler, objgraph) are great tools. But I wanted something I could drop on any function in 30 seconds and get a readable answer from. Also, honestly I wanted to understand what's happening at the GC and tracemalloc abstraction layer in Python. The best way I know to understand something is to build on top of it. So I built MemGuard over a weekend. What it does: Drop @memguard() on any function and after every call you get: Net memory retained (the actual leak signal) Peak vs net ratio — catches memory churn even when net looks clean Per-type gc object count delta tells you what is accumulating, not just how much Cross-call trend detection if net grows every call, it flags it Allocation hotspots via tracemalloc exact file and line Zero dependencies. Pure stdlib gc, tracemalloc, threading. @memguard() def process_batch(records): That's it. It also works as a context manager if you want to profile a block rather than a function. Biggest thing I learned building this: Python's gc and tracemalloc expose far more than most people use day to day. The object-reference graph alone tells a story that byte counts miss entirely. Repo: https://lnkd.in/gdjkHvfb Would love feedback from anyone who's dealt with Python memory issues in production. #Python #Django #SoftwareEngineering #OpenSource #BackendDevelopment #MemoryManagement
To view or add a comment, sign in
-
-
I've been using @decorators But Today I finally understood what happens in memory when Python sees that @ symbol. Here's the full picture — with actual RAM addresses 👇 When Python runs your script, it creates function objects in memory immediately: decorator() → stored at address 0x7668...2e0 just_a_func() → stored at address 0x7668...380 The moment you call decorator(just_a_func), something new happens: A brand new object do_something() is born at 0x7668...420 Inside do_something(), the func argument holds a reference to just_a_func's address — 0x7668...380 The original just_a_func() is never modified. It stays at the same address. So @decorator is just clean syntax for: decorated = decorator(just_a_func) That's it. No magic. Just references. Now the FastAPI part — and this is where it gets interesting. @app.get("/ping") is NOT a decorator itself. It's a function that RETURNS a decorator. Under the hood: — app.get("/ping") calls APIRouter.api_route() — api_route() returns a decorator(func) function — that decorator calls add_api_route(path, func) — your route function is now registered in the app's memory state You can actually do this manually without @ syntax: decorator = app.get("/ping") decorated = decorator(new_route) Same result. Just less elegant. The deeper I go into FastAPI internals, the more I appreciate how cleanly it's built. Everything is explicit, traceable, and follows Python's own function object model. This is what "learning in public" looks like — going beyond the docs and into the source code. What concept in your stack did you finally understand by reading the source code? #Python #FastAPI #Decorators #LearningInPublic #BackendDevelopment #100DaysOfCode #SoftwareEngineering #PythonTips #WebDevelopment For More In Dept Visit : https://lnkd.in/d7-rqhzQ
To view or add a comment, sign in
-
-
Mutable default arguments — the bug that's been in your code for years Most Python developers have shipped this bug. They just don't know it yet. def add_item(item, items=[]): items.append(item) return items Looks innocent. Isn't. Most people think the empty list is created fresh on every call. It's not. The default value is evaluated exactly once — when the function is defined. The same list object is reused on every call where you don't pass items explicitly. Call it three times without arguments and you don't get three lists with one item each. You get one list with three items, growing across every call you forget to make. In production this shows up as: a function that caches results between requests when you didn't ask it to. State leaking across users. Tests that pass alone and fail in a suite. The fix is one line: def add_item(item, items=None): if items is None: items = [] items.append(item) Mutable defaults are not a feature. They're a sharp edge. Sentinel-and-rebuild is the only safe pattern. #PythonInternals #Python #DataEngineering #SoftwareEngineering #Developer #PythonDeveloper #Backend #CodingInterview #Developers #Programming #Learning #PythonTips
To view or add a comment, sign in
-
🚀 Turn any Python CLI script into a modern GUI – with zero extra dependencies. I just open‑sourced PyScript-to-GUI, a tool that instantly wraps your command‑line scripts into a clean, functional graphical interface. ⚡ No more boring terminals. Your users get a real window with dark mode, real‑time output, and interactive input dialogs – without writing a single line of GUI code. ✨ Key features: ✅ Zero external dependencies – uses only tkinter (built into Python) ✅ Smart input() handling – automatically converts prompts into pop‑up dialogs ✅ Live logging – all print() output appears in a scrollable terminal‑style area ✅ Multi‑threaded – the GUI never freezes, even during heavy tasks ✅ Hacker aesthetic – dark grey + lime green theme, ready to impress 🔧 Perfect for: Sharing your scripts with non‑technical colleagues Building quick internal tools with a professional look Teaching Python without scaring beginners with the terminal 🔗 GitHub repo: https://lnkd.in/dDpXCYSk 👨💻 Built by NULL200OK – because every script deserves a beautiful face. #Python #GUI #Tkinter #OpenSource #DeveloperTools #CLItoGUI #PyScriptToGUI #Coding
To view or add a comment, sign in
-
Claude prompt tip: when working on something that is likely to require a lot of code changes (Ex: function, package renames, updating the entire code base with a new pattern), I’ve encountered many times this issue: 1. Claude is tempted to use Python scripts to minimize the token usage. However, in 90% of the time it fails to do it properly because the Python script will not take into account edge cases. 2. Claude is also tempted to do it all in one go, but this is usually very slow... and sometimes even fails. It is more efficient and reliable to do it in small batches. 3. If you ask Claude to do your large code change, it will do it immediately, and this is not a good idea: as a developer, you still need to be in control of the tool and verify that Claude is not going to go outside of its boundaries. Here is a prompt suggestion that will help you get more reliability and visibility on Claude changes: ______ <your instructions and great ideas here> Work in small batches, do not use Python scripts. Provide a plan. _______ Don’t hesitate to share your prompt tips!
To view or add a comment, sign in
-
Day 7/10 🚀 This is where your code grows up. Modules & Packages — the foundation of every scalable Python project. Without them? Spaghetti code, repetition, no structure. With them? Clean, reusable, production-ready code. 📋 What I covered today: 01 → Modules & package structure 02 → Creating & importing .py files 03 → init.py & sub-packages 04 → Import styles — import, from, alias 05 → Relative vs absolute imports 06 → Standard library — os, json, datetime, re 07 → Third-party packages — pip, numpy, pandas 08 → Virtual environments & requirements.txt 09 → Mini Project — Config Loader Package Built a small config package with loader & validator modules — a real-world pattern used in production apps. Day 1 ✅ Day 2 ✅ Day 3 ✅ Day 4 ✅ Day 5 ✅ Day 6 ✅ Day 7 ✅ 3 more to go. Drop a 📦 if you’ve ever put everything in one giant .py file 😄 #Python #Modules #Packages #DataEngineering #LearningInPublic #CleanCode #10DaysOfPython #SoftwareEngineering
To view or add a comment, sign in
-
UV is one of the best Python tools I've used recently. But it taught me something the hard way. A few weeks ago, I created a virtual environment with uv venv, assumed it was active, and started installing packages. I thought everything was fine. Only later did I realize: packages had been installed globally, not in the project environment. Here's what I was missing: UV doesn't auto-activate virtual environments the way Poetry or Conda might. When you run uv run python script.py, UV uses the project environment internally—it looks active, but your shell session isn't actually modified. There's no prompt change. No visual indicator. This is intentional design, not a bug. UV is explicit, not implicit. It separates environment creation from environment activation. But that separation can catch you off-guard. The correct workflows: -Option 1 (recommended): Use uv run uv run python script.py No need to manually activate anything. UV handles it internally. -Option 2: Manually activate the venv source .venv/bin/activate Then install or run as normal. This gives you shell-level control. -Option 3: Use uv pip install uv pip install package_name This ensures installation happens in the uv-managed environment, not globally. The lesson: understand the tool's philosophy. UV prioritizes explicitness over convenience. That's actually a strength—it makes behavior predictable once you understand the pattern. But it requires intentional workflows. Big credit to Astral for building a fast, thoughtful package manager. This wasn't a flaw—it was me not reading the documentation carefully enough. If you use UV, make this part of your muscle memory. Small habit, saves debugging time. #Python #UV #PackageManagement #DeveloperExperience #SoftwareEngineering #Astral #DevTools #BestPractices #Python3 #VirtualEnvironments
To view or add a comment, sign in
-
-
Alex Marin, our application packaging expert, just published a personal story on his early days in endpoint management. It was so good that it was accepted on the reputable Level Up Coding on Medium.com. Long story short: a "simple" Python script turned into a total production nightmare. And how software deployment fails at scale. “The culprit wasn’t a server outage or a complete network failure. It was a Python script! A small one. One that you might consider as harmless. The type of script that works flawlessly on one machine, then ten, then one hundred. But that morning, it had to run on thousands of machines. That’s when everything fell apart…” Check out the full story on how he turned it around: https://lnkd.in/dB8pN_By #Python #EndpointManagement #TechLessons #SoftwareEngineering #DevOps
To view or add a comment, sign in
-
From script to system — Part 5 (Writing fewer tests with better coverage using parametrize) It might be tempting to write repetitive tests like this: - same function - different inputs/outputs - copy paste over and over It works at the start... but what if the function changes. Editing the same thing multiple times is not fun. In other words, the tests doesn’t scale What helped: - pytest parametrize Instead of multiple tests: - Define inputs and expected outputs in one place - Write a single test that runs the same function with the different expected values/results Example mindset: - Focus on scenarios, not individual tests What this improves: - Less duplication - Better coverage with fewer lines - Easier to extend when new cases appear Cleaner tests More confidence Less maintenance Reference: https://lnkd.in/esfZgVuU Next: Run Your Tests Automatically #Python #Pytest #Testing #Automation #CodeQuality #DevOps #SoftwareDevelopment #LearningInPublic
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