Function-based decorators use closure to remember state. Class-based decorators use self. Same concept, different container. And the container matters when your decorator needs to count calls, expose a .reset() method, or manage complex configuration. I just published a bonus article in my Python Decorators series on "Build, Break, Learn" that walks through when and why to use a class as a decorator, with practical examples. Closures hold state. Classes give it a home. Read it here: https://lnkd.in/dqbcztqs New to the series? Start from Part 1, link in the comments. #Python #PythonDecorators #SoftwareEngineering #TechnicalWriting #BuildBreakLearn
Class Decorators vs Closures in Python
More Relevant Posts
-
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
-
-
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
-
-
😊❤️ Todays topic: Topic: Abstraction in Python: ============= Abstraction means hiding implementation details and showing only essential features. You focus on what an object does, not how it does it. Real Idea: When you use a mobile phone, you press buttons without knowing internal circuits. That’s abstraction. In Python, abstraction is implemented using abstract classes. from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmethod def start(self): pass Creating a child class: class Car(Vehicle): def start(self): print("Car starts with key") c = Car() c.start() Output: Car starts with key Important Rule: You cannot create an object of an abstract class. v = Vehicle() # ❌ Error Explanation: ABC → Abstract Base Class @abstractmethod → method that must be implemented in child class Key Points: Hides implementation details Forces child classes to implement required methods Improves design and consistency Interview Insight: Abstraction ensures a clear contract for child classes, making large systems easier to manage. Quick Question: What will happen if a child class does not implement an abstract method? #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
🚀 Level Up Your Python Code with collections.Counter 🐍 Still using manual loops and dictionaries to count items? There’s a smarter, cleaner way—meet Counter, a powerful subclass of Python’s built-in dict designed specifically for counting. Here’s why it deserves a spot in your toolkit 👇 🔹 Effortless Counting Just pass any iterable (list, string, tuple, etc.), and it automatically calculates frequencies. Keys are elements, values are their counts—simple and efficient. 🔹 No More KeyError Access a missing element? No crash. Counter returns 0 by default. 🔹 Supports Negative & Zero Counts Unlike regular counting logic, Counter handles zero and even negative values seamlessly. 🔹 Built-in Power Methods most_common(n) → Get top n frequent elements instantly update() & subtract() → Add or remove counts easily elements() → Expand back into elements based on counts 🔹 Multiset Operations Made Easy Perform arithmetic operations directly: + → Combine counts - → Subtract counts & → Intersection (minimum counts) | → Union (maximum counts) 💡 Why it matters? Cleaner code, fewer bugs, and faster development. No need to reinvent counting logic—Counter handles it elegantly. #Python #PythonCounter #PythonCollections #DataStructures #DataScience #PythonProgramming #DeveloperCommunity #CodingTips #LearnPython
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
-
-
🐍 Codédex March Challenge 2026: My Python Gallery What is this project about? During the entire month of March, I took part in the Codédex Challenge, solving a different logic problem every day using Python. Instead of leaving all my solutions hidden in folders and text files that no one reads, I decided to build this website to showcase my work in a visual and engaging way. This application is literally an interactive gallery for my code. You enter one place and can browse day by day to see how I think and how I solve problems step by step. What can you see in each day of this gallery? - The Problem: What each daily challenge was about (from decoding secret messages to calculating time differences or finding unique words). - My Python Code: The exact script I wrote to solve it, displayed in a block that simulates a real code editor inside the web app. - My Explanation: A short summary where I explain how I solved it and why I chose certain loops, lists, or functions to reach the result. The Approach The main goal here is to let my code speak for itself. Instead of overloading it with boring technical descriptions, I built a super clean and easy-to-use interface (with both light and dark mode) whose only purpose is to let you read my Python code comfortably, understand my daily logic, and see the result of 31 days of consistency. 🔗 Explore the Project 🌐 Live Website: https://lnkd.in/emixPMTw 💻 GitHub Repository: https://lnkd.in/ek_-HUbh
To view or add a comment, sign in
-
-
I just published a new post on what an FP-style engineering workflow can look like in Python before much code exists. The argument is practical. Too many implementations start by sketching a class and letting requirements, state, and edge-case policy collect inside it. I think the better starting point is a short requirement list, a clear data-flow sketch, explicit domain types, function signatures, and a few contract-defining tests. The TF-IDF vectorizer in the post is just a compact example for showing that workflow. For those who build Python systems for data work, ML tooling, or any codebase where fit-time and transform-time logic can get tangled, this may be useful: https://lnkd.in/eUbUW8q5
To view or add a comment, sign in
-
Tiny Python upgrade for cleaner analytics code: Use Counter instead of manual dict increments. You get frequency maps in one pass and top-N insights with most_common(). Less boilerplate, fewer mistakes, faster review. Mini pattern: - counts = Counter(values) - top = counts.most_common(3) - act on thresholds #Python #CodingTips #Backend #DevTips #SoftwareEngineering
To view or add a comment, sign in
-
-
If you work with Python, here’s a small concept that can make your code more efficient: generator expressions. Most developers learn list comprehensions early: 𝘀𝗾𝘂𝗮𝗿𝗲𝘀 = [𝘅 * 𝘅 𝗳𝗼𝗿 𝘅 𝗶𝗻 𝗿𝗮𝗻𝗴𝗲(𝟭𝟬)] But if you only need to iterate once, a generator expression may be a better choice: 𝗳𝗼𝗿 𝘀𝗾𝘂𝗮𝗿𝗲 𝗶𝗻 (𝘅 * 𝘅 𝗳𝗼𝗿 𝘅 𝗶𝗻 𝗿𝗮𝗻𝗴𝗲(𝟭𝟬)): 𝗽𝗿𝗶𝗻𝘁(𝘀𝗾𝘂𝗮𝗿𝗲) Key differences betwen list-comp and generators is: • Generator expressions use parentheses () and produce values one at a time, only when needed. • List comprehensions use brackets [] and create the full list in memory immediately. Why does this matter? • Lower memory usage • Faster startup for large datasets • Better for streaming data • Ideal for one-pass processing Imagine processing 1 million records. A list comprehension builds 1 million items first, a generator expression yields one item at a time. That difference can be huge in real systems. Rule of thumb: • Need all values now or multiple times? Use a list comprehension • Need to consume items once? Use a generator expression Efficient Python is often about choosing the right tool, not writing more code. #python #programming #softwareengineering #cleancode #performance #generators
To view or add a comment, sign in
-
🚀 Decorator Use Cases: Timing Function Execution (Python) Decorators are excellent for measuring the execution time of functions. By wrapping the function with a timer, you can easily track how long it takes to run. This is useful for performance optimization and identifying bottlenecks. The time can be logged or printed for analysis. Learn more on our app: https://lnkd.in/gefySfsc #Python #PythonDev #DataScience #WebDev #professional #career #development
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
Read part 1 here: https://blog.moussaamzat.dev/understanding-python-decorators-from-scratch