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
Understanding Python Decorators and FastAPI Internals
More Relevant Posts
-
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
To view or add a comment, sign in
-
Day 14/365: Rotating a List by k Positions in Python 🔁📦 Today I worked on a classic array/list problem: rotating a list to the right by k positions without using built‑in shortcuts. The goal: Given a list l = [1, 2, 3, 4, 5] and k = 2, the output should be: [4, 5, 1, 2, 3] Here’s the logic I used: I run a loop k times, because I want to rotate the list to the right by k positions. In each rotation: I first store the last element: last = l[-1] Then I shift every element one step to the right: Starting from the end and moving backwards: for j in range(len(l)-1, 0, -1): I set l[j] = l[j-1] so each position takes the value from its previous index. After this loop, the first position l[0] is empty (logically), so I place the old last element there: l[0] = last After repeating this process k times, the list is rotated right by k positions. 💡 What I learned: How to manually rotate a list step by step, instead of relying on slicing tricks. How backward loops work in Python using range(start, stop, step) with a negative step. Why thinking in terms of “shifting” elements helps in many array/list problems (rotations, circular buffers, games, etc.). How repeating a simple transformation k times can solve problems without complex math. Next, I’d like to explore: Handling large k values efficiently (e.g., using k % len(l)). Rotating to the left instead of the right. Solving the same problem using slicing and comparing both approaches. Day 14 done ✅ 351 more to go. Got any other list/array transformation problems (like cyclic shifts, sliding windows, or in‑place rearrangements)? Drop them in the comments—I’d love to try them next. #100DaysOfCode #365DaysOfCode #Python #Lists #LogicBuilding #DataStructures #CodingJourney #LearnInPublic #AspiringDeveloper
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
-
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
-
-
Haven't posted in a while and decided to post this small project that might help someone. I usually like having something running in the background while I’m coding or drawing diagrams , but most apps I tried were either too heavy or just not what I wanted. So I wrote a small Python script where you can drop in your own GIF and it just sits there on your screen. No window borders, no distractions, doesn’t get in the way, and barely uses any memory. It’s nothing crazy, just a simple aesthetic thing, but I’ve been using it a lot more than I expected. If anyone wants to try it or tweak it, I left the repo below. https://lnkd.in/dWFuTPH5
To view or add a comment, sign in
-
🧠 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
-
-
Clean code isn't clever. It's clear. 5 Python patterns every developer should know: 1️⃣ Flatten nested list: flat = [x for sub in nested for x in sub] 2️⃣ Merge dicts (Python 3.9+): merged = dict_a | dict_b 3️⃣ Most frequent item: max(set(lst), key=lst.count) 4️⃣ Swap variables: a, b = b, a 5️⃣ Read + strip file lines: lines = [l.strip() for l in open("file.txt")] --------------- These aren't tricks. They're idiomatic Python. When your code communicates intent: ✅ Reviews go faster ✅ Bugs surface sooner ✅ Onboarding is smoother Write for the developer reading it at 2am before a deployment. That developer is usually you. #Python #CleanCode #Programming #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
#Flask turns 16 today 🎉 Did you know Flask started as an April Fools’ joke by Armin Ronacher? What began as a small experiment became one of the most widely used Python web frameworks. 16 years later, it’s still powering everything from quick prototypes to production apps. 💡 About the original “Denied” microframework: Armin created “Denied” to poke fun at early microframeworks that avoided dependencies by packing everything into a single file. So he did exactly that – embedding Jinja2 and Werkzeug as a base64-encoded `.zip` inside a single Python file. A month later, the idea evolved into something real. That project became Flask – turning a joke into a framework developers still rely on today. What do you use Flask for the most?
To view or add a comment, sign in
-
-
Flask has long been my go-to for deploying ML models. It's easy to use and lightweight. Companies sometimes assume that using custom ML models means having to adopt [insert big, complicated framework here]. Maybe they'll need that down the road. Maybe. But for those first steps, Flask is the way to go. (I can already see the confused looks, so: yes, I still write code and build models! It's no longer my everyday. But it's my often-enough.)
#Flask turns 16 today 🎉 Did you know Flask started as an April Fools’ joke by Armin Ronacher? What began as a small experiment became one of the most widely used Python web frameworks. 16 years later, it’s still powering everything from quick prototypes to production apps. 💡 About the original “Denied” microframework: Armin created “Denied” to poke fun at early microframeworks that avoided dependencies by packing everything into a single file. So he did exactly that – embedding Jinja2 and Werkzeug as a base64-encoded `.zip` inside a single Python file. A month later, the idea evolved into something real. That project became Flask – turning a joke into a framework developers still rely on today. What do you use Flask for the most?
To view or add a comment, sign in
-
-
The "Shadow" Fix: Python Version Compatibility **Hook:** Building for the "Latest & Greatest" is easy. Building for the "Real World" is where the engineering gets messy. **Body:** While finalizing my Enterprise RAG pipeline, I hit a silent production-breaker: A `TypeError` buried deep in a third-party dependency. The culprit? The `llama-parse` library uses Python 3.10+ type union syntax (`|`), but the production environment was locked to Python 3.9. Result: Immediate crash on boot. Instead of demanding a system-wide upgrade—which isn’t always possible in locked-down enterprise environments—I implemented a **Graceful Fallback Logic**: ✅ **Dynamic Imports**: Wrapped the cloud-parser initialization in a guarded `try-except` block. ✅ **Smart Routing**: If the Python environment is incompatible, the system automatically redirects to a local, high-fidelity `PyMuPDF` parser. ✅ **System Resilience**: The app stays online, the UI remains responsive, and 99% of RAG functionality remains available without a single user noticing a failure. Real Engineering isn't just about using the best tools—it’s about writing code that doesn't break when the environment isn't perfect. #Python #SoftwareEngineering #RAG #AIEngineering #SystemDesign #Resilience
To view or add a comment, sign in
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