Topic 12/100 🚀 🧠 Topic 12 — Mixins Ever wanted to add specific features to a class without creating a messy, deep inheritance tree? 🧬 That’s where Mixins come in. 👉 What is it? A Mixin is a specialized type of multiple inheritance. It’s a class that provides methods to other classes but isn't meant to stand on its own. Think of it as a "plugin" for your classes. 👉 Use Case: Used in real-world applications for: Logging: Adding log() capabilities to any service. Authentication: Giving specific views the ability to check permissions. JsonSerialization: Adding a to_json() method to various data models. 👉 Why it’s Helpful: Modularity: Keeps small features separated. Avoids Duplication: Write once, "mix in" everywhere. Clean Hierarchy: Keeps your main class inheritance focused on what the object is, while Mixins handle what it does. 💻 Example: Python class LoggerMixin: def log(self, message): print(f"Log: {message}") class MyService(LoggerMixin): def run(self): self.log("Service is running") service = MyService() service.run() 🧠 What’s happening here? MyService isn't necessarily a "type of" Logger, but it wants the "ability" to log. By inheriting from LoggerMixin, it gains that specific tool without a complex setup. ⚡ Pro Tip: In frameworks like Django, Mixins are everywhere (like LoginRequiredMixin). They are the secret to keeping large codebases organized and DRY (Don't Repeat Yourself). 💬 Follow this series for more Topics #Python #BackendDevelopment #100TopicOfCode #SoftwareEngineering #LearnInPublic #Mixins #CleanCode
Mastering Mixins in Python for Clean Code
More Relevant Posts
-
💡 Rearranging a Linked List In-Place — A Clean Trick I Learned Today Worked on the Odd-Even Linked List problem today, and it turned out to be a great reminder that pointer manipulation doesn’t have to be messy. The task sounds simple: 👉 Group all odd-indexed nodes together followed by even-indexed nodes But the challenge is to do it: In-place (no extra space) In one pass 🔑 Approach that clicked for me: Maintain two pointers: odd → tracks odd-position nodes even → tracks even-position nodes Keep a reference to the head of the even list (even_head) Rewire pointers while traversing Finally, connect odd list to even list ✨ What I liked: No extra data structures Pure pointer manipulation O(n) time and O(1) space Python code : https://lnkd.in/gCB9ZGaq 🧠 Biggest takeaway: Linked list problems often look tricky, but once you clearly track pointers and their roles, the solution becomes surprisingly elegant. Have you faced a linked list problem that looked hard but turned out simple after breaking it down? 👇 #LinkedList #DataStructures #CodingInterview #Python #ProblemSolving #LeetCode Rajan Arora
To view or add a comment, sign in
-
-
I’ve been polishing a personal project called ExcelAlchemy, and it’s now at its first stable public release: 2.0.0. ExcelAlchemy is a schema-driven Python library for Excel import/export workflows. It turns Pydantic models into typed workbook contracts: generate templates, validate uploads, write failures back to rows and cells, and keep workbook-facing output locale-aware. A lot of the work in this project was not just about making it work, but about making it feel like a real library: - modern Python typing and stricter static analysis - a cleaner validation pipeline around Pydantic v2 - protocol-based storage boundaries - pandas removed from the runtime path - contract tests, Ruff, Pyright, and release-focused documentation I also treated the repository as a design artifact: not just code, but a record of architectural tradeoffs, migration strategy, and package design decisions. Repo: https://lnkd.in/gV9jC87W #Python #OpenSource #Pydantic #ExcelAutomation #SoftwareArchitecture #DeveloperTools
To view or add a comment, sign in
-
-
Stop fixing, start scaling. 🚀 We’ve all been there: you build a scraper, it works perfectly, and then—one small website update later—your entire pipeline is broken. It’s a frustrating cycle that holds your data back. It’s time to move away from fragile, "quick-fix" scripts and toward enterprise-grade data infrastructure. We’ve put together a complete guide to help you master web scraping with Python and build systems that actually last. Check out the full guide here: https://lnkd.in/g-NQk3SJ #WebScraping #Python #DataEngineering #BigData #Boundev
To view or add a comment, sign in
-
-
Day 5 of #50DaysOfDjango ◆URLs & Routing in Django Today I learned how Django connects URLs to views This is the starting point of every user request. Response Flow: URL urls.py → View urls.py acts like a traffic controller Static URL: /about/ Dynamic URL: /user/5/ (passes data) Example: Python path('user/<int:id>/', views.user_profile) Challenge: Create 3 URLs + 1 dynamic route and connect them to views Now I understand how Django handles requests behind the scenes
To view or add a comment, sign in
-
-
Your API isn’t slow. Your pagination is. 📉 It worked perfectly… until your data grew. Then every page got slower than the last. Nothing changed in your code. Only the dataset got bigger. The culprit? Offset pagination. The deeper the page, the more rows your database has to scan and skip. Page 1 → fast Page 1000 → painful Same query. Very different cost. The fix wasn’t caching. It was switching to cursor-based pagination. No skipping. Just jumping. In Django REST Framework, this was as simple as: Use 'CursorPagination' instead of 'PageNumberPagination'. Constant performance. Even at scale. Most performance issues aren’t complex. They’re patterns that don’t scale. Most developers don’t notice this until it’s too late. #BackendDevelopment #Django #Python #WebDevelopment #SoftwareEngineering #APIPerformance #DatabaseOptimization #SystemDesign #ScalableSystems #DjangoRESTFramework
To view or add a comment, sign in
-
-
Most developers use __init__ every day. But here’s the catch: We use it so often that we stop questioning how objects are actually created. And that’s where __new__ quietly gets ignored. The truth is: 👉 __𝐧𝐞𝐰__ creates the object 👉 __𝐢𝐧𝐢𝐭__ initializes the object Python doesn’t create objects in one step. It happens in two phases: 1️⃣ Memory is allocated → __new__ 2️⃣ Object is configured → __init__ A quick example: class Example: def __new__(cls): print("Creating instance") return super().__new__(cls) def __init__(self): print("Initializing instance") obj = Example() 𝘖𝘶𝘵𝘱𝘶𝘵: Creating instance Initializing instance Here’s the part most people never think about 👇 You’ve probably never written __new__. Yet your objects still get created perfectly. Why? Because Python is already doing this behind the scenes: obj = MyClass.__new__(MyClass) MyClass.__init__(obj) And if you don’t define __new__, Python uses: object.__new__() We treat __init__ like a constructor. But technically… it isn’t. 👉 𝑻𝒉𝒆 𝒓𝒆𝒂𝒍 𝒄𝒐𝒏𝒔𝒕𝒓𝒖𝒄𝒕𝒐𝒓 𝒊𝒔 __𝒏𝒆𝒘__. ⚡ Why __new__ matters: - Controls object creation - Used in Singleton patterns - Important for immutable types (int, str, tuple) - Can even return a different object ⚡ What __init__ actually does: - Just initializes the already-created object - Cannot create or return a new instance - Always returns None 💡 Real takeaway: We rely on __init__ so much that we rarely think about what happens before it. Understanding __new__ is what shifts you from: 👉 writing Python code to 👉 understanding how Python actually works Once you see it, you can’t unsee it 🙂 #Python #PythonProgramming #SoftwareDevelopment #BackendDevelopment #Coding #Programming #LearnToCode #DeveloperMindset #TechCareers #SoftwareEngineer #CleanCode #ProgrammingConcepts
To view or add a comment, sign in
-
-
🚀 Day 8/30 of My LeetCode Journey (Python + SQL) Staying consistent and leveling up every day! 💻🔥 🔹 **SQL Problem of the Day** 👉 *Find Customer Referee* Given a `Customer` table, write a query to find the names of customers who are either: • Not referred by customer with id = 2 • OR not referred by anyone 💡 *Key Concept:* Filtering with conditions (`!= 2` OR `IS NULL`). 🔹 **Python Problem of the Day** 👉 *Merge Sorted Array* Given two sorted arrays, merge them into a single sorted array in-place without returning a new array. 💡 *Key Concept:* Two-pointer approach from the end for efficient in-place merging. Every problem is helping me think more efficiently and write better code ⚡ Day 8 done ✅ #LeetCode #30DaysChallenge #Python #SQL #CodingJourney #Consistency #ProblemSolving #Learning
To view or add a comment, sign in
-
One of the most common FastAPI mistakes is reusing SQLAlchemy models as Pydantic response schemas. This doesn't just couple your layers—it makes it easy to accidentally expose fields like hashed passwords. In my latest post, I share 8 Sections of battle-tested patterns for structuring your FastAPI applications: 1️⃣ Centralized Config: Using pydantic-settings instead of scattered os.environ calls. 2️⃣ Dependency Injection: Leveraging Depends() for cleaner auth and DB sessions. 3️⃣ Business Logic: Moving core logic into pure Python service functions for easier unit testing. 4️⃣ Error Handling: Using app-level exception handlers to remove "try/except" noise from routes. Swipe through the PDF for the code examples and folder structures! ➡️ #FastAPI #Python #BackendDevelopment #WebDevelopment #CleanCode
To view or add a comment, sign in
-
DevLog Day 13. Two medium level problems today and honestly both of them taught me something new. First was Sort Colors. The problem sounds deceptively simple, sort an array of 0s, 1s and 2s in ascending order. Easy right? The catch is no built in sorting library and it has to run in O(n) TC. That changes everything. I tried every combination I could think of with two pointers but the edge cases kept breaking my logic. Eventually I peeked at the hints in the problem description and they were pointing toward Counting Sort. The idea is simple, track the frequency of each number using its index as a key and then recreate the array from those frequencies. Once I understood that it took me a minute to solve it. One of those moments where the algorithm just clicks. Then came Rotate Array. There are multiple ways to solve it but three core approaches. I figured out two on my own and got stuck on the third. The hint was that array rotation is related to reversing the array in a specific order. Once that clicked the pattern was obvious. One important optimization worth noting is to use the modulo operator for k because k can be larger than the array length and without it you would go out of bounds. Also I switched from C++ to Python for DSA. The boilerplate in C++ was getting in my way and I kept getting distracted by syntax instead of focusing on the actual logic. Python just gets out of the way. Best decision I have made in this prep so far. Later I covered Monolithic vs Microservice architecture in System Design. #DevLog #BuildInPublic #DSA #LeetCode #Python #SystemDesign #LearningInPublic #IndieHacker #WebDevelopment
To view or add a comment, sign in
More from this author
-
🚀 Just Took My First Steps with the OpenAI Python API — Here's How Easy It Is!
HIMANSHU MAHESHWARI 2mo -
Beyond the Hype: A Practical Guide to Integrating AI & ML Into Your Projects
HIMANSHU MAHESHWARI 6mo -
🧠 Laravel Jobs & Queues vs Django Celery: A Backend Developer's Guide to Async Task Management 🚀
HIMANSHU MAHESHWARI 1y
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