Diving Deep into Python Magic Methods . Recently, I started exploring the internals of Python’s magic methods — those special methods that begin and end with double underscores (__). These aren’t typically called directly; instead, Python invokes them behind the scenes to enable powerful behaviors. These methods can be broadly categorized into: * Callable Objects → __call__() * Iterator Pattern → __init__(), __iter__(), __next__() * Finite Iterators * Context Managers ¥ Understanding the for Loop Internals A for loop in Python is actually built on the Iterator Protocol. Under the hood, it relies on three key magic methods: __init__() → initializes the object __iter__() → returns the iterator object (usually self) __next__() → returns the next value in the sequence ⚙️ How the for Loop Works Internally 1)iter(obj) is called automatically This invokes __iter__() and returns an iterator 2) next(obj) is called repeatedly This invokes __next__() and fetches values 3)Loop continues until StopIteration is raised Without it, the loop runs infinitely 🧠 Example: Custom Iterator class Repeat: def __init__(self, msg): self.msg = msg def __iter__(self): return self def __next__(self): return self.msg This will print the same message infinitely because StopIteration is never raised. Key Insight A for loop is essentially syntactic sugar over a while loop using the iterator protocol. Understanding this gives you deeper control over debugging and helps you identify the root cause of issues in iteration-heavy code. ✨ Once you understand what's happening behind the scenes, Python feels a lot less “magical” and a lot more predictable. For better understanding and clarity I suggest referring the image attached. Till then Happy Sunday, Happy learning and Happy growing. #Python #Programming #SoftwareDevelopment #Coding #PythonInternals #OOP #Developers #Learning #Tech #CSStudents #Debugging
Unlocking Python's Magic Methods for Deeper Control
More Relevant Posts
-
F-strings in Python — Not Just Cleaner. Fundamentally Better. Python has had three ways to format strings over its history. If you’ve only learned the language recently, you might not have encountered the older two — but you will, because they still appear in legacy codebases, documentation, and tutorials written before Python 3.6. The first was % formatting, borrowed from C: name = "Andres" print("Hello, %s. You have %d messages." % (name, 5)) It works. But the syntax is cryptic, the order of arguments is error-prone, and it becomes harder to read as soon as you add more than one variable. The second was .format(), introduced in Python 3.0: print("Hello, {}. You have {} messages.".format(name, 5)) An improvement — more explicit, more flexible. But the variables and the placeholders are still separated. To understand what goes where, your eyes have to travel back and forth across the line. Then Python 3.6 introduced f-strings: print(f"Hello, {name}. You have {5} messages.") The variable lives inside the string, exactly where it appears in the output. No positional arguments. No external references. The code reads the way the sentence reads. Beyond readability, f-strings also evaluate expressions directly inline — which means you can do this: hours = 7.5 print(f"Weekly total: {hours * 5} hours") No intermediate variable needed. And in terms of performance, f-strings are consistently faster than .format() because they are parsed closer to compile-time rather than evaluated fully at runtime. Knowing all three methods matters. Understanding why f-strings became the standard tells you something about how Python evolves — always toward clarity. #Python #PythonMOOC2026 #BackendDevelopment #SoftwareEngineering #LearningInPublic #UniversityOfHelsinki
To view or add a comment, sign in
-
-
Python: sort() vs sorted() Have you ever had to pause for a second and think: “Do I need sort() or sorted() here?” 😅 This is the common Python confusions. Let’s clear it up. 🔹 list.sort() ◾ A method (belongs to list objects) ◾ Works only on lists ◾ Sorts the list in-place ◾ Changes the original list ◾ Returns None Example: numbers = [3, 1, 4, 2] numbers.sort() print(numbers) # [1, 2, 3, 4] 🔹 sorted() ◾ A function (built-in Python function) ◾ Returns a new sorted list ◾ Does NOT change the original ◾ Works on any iterable Example: numbers = [3, 1, 4, 2] new_numbers = sorted(numbers) print(new_numbers) # [1, 2, 3, 4] print(numbers) # [3, 1, 4, 2] The key difference: sort() → changes your original data sorted() → keeps your original data safe 💡 Quick way to remember: 👉 If you want to keep the original, use sorted() 👉 If you want to modify the list directly, use sort() #Python #Programming #LearnPython #DataScience #LearningJourney #WomenInTech
To view or add a comment, sign in
-
-
🔺 BIG Python Sin: Using a mutable default argument Don't use a mutable object as a default argument. Default arguments in Python are evaluated once, at function definition time, not each time the function is called. If you have a default argument like: items=[], it will be shared across all calls, and you will get an accumulating state you didn’t ask for. # Mutable default argument def add_item(item, my_list=[]): my_list.append(item) return my_list Output print(add_item(1)) # [1] print(add_item(2)) # [1, 2] print(add_item(3)) # [1, 2, 3] 👑 The best way is to have an immutable object as a default argument. That way, each call will get a fresh list as in the example below. def add_item(item: int, my_list: Optional[List[int]] = None) -> List[int]: if my_list is None: my_list = [] my_list.append(item) return my_list Default arguments are evaluated at function definition time, not call time. When in doubt, use None as the default and create the mutable object inside the function! Learn About Python classes. Full Classes video on YouTube. Link below Link: https://lnkd.in/eJ_zMQis
To view or add a comment, sign in
-
-
Stop using + to join strings in Python! 🐍 When you are first learning Python, it is tempting to use the + operator to build strings. It looks like this: name = "Gemini" status = "coding" print("Hello, " + name + " is currently " + status + ".") The Problem? In Python, strings are immutable. Every time you use +, Python has to create a brand-new string in memory. If you are doing this inside a big loop, your code will slow down significantly. The Pro Way: f-strings (Fast & Clean) Since Python 3.6, f-strings are the gold standard. They are faster, more readable, and handle data types automatically. The 'Pro' way: print(f"Hello, {name} is currently {status}.") Why use f-strings? Speed: They are evaluated at runtime rather than constant concatenation. Readability: No more messy quotes and plus signs. Power: You can even run simple math or functions inside the curly braces: print(f"Next year is {2026 + 1}") Small changes in your syntax lead to big gains in performance. Are you still using + or have you made the switch to f-strings? Let’s talk Python tips in the comments! 👇 #Python #CodingTips #DataEngineering #SoftwareDevelopment #CleanCode #PythonProgramming
To view or add a comment, sign in
-
I made a very classic beginner mistake — I underestimated Python. I thought I could skip the "essentials" and jump straight into Machine Learning like I had a mod. But ML doesn’t really do shortcuts. Turns out, it expects you to actually understand what you are doing. After spending time working with fundamentals like lists and dictionaries, I had a simple but uncomfortable realization: If your Python foundation is weak, Machine Learning doesn’t feel advanced— it just feels like you’re constantly struggling to keep up in a language you barely speak. So I’m doing the sensible thing now: going back and strengthening the basics. Yes, the “boring” stuff I tried to rush past. And honestly, Python was never the problem. My overconfidence was. #Python #MachineLearning #ProgrammingBasics #LearnToCode #NeverStopLearning #100DaysOfCode #TechLearning
To view or add a comment, sign in
-
Integer Division and Modulo in Python — Two Operators Worth Understanding Deeply Most arithmetic operators in Python do exactly what you expect. Addition, subtraction, multiplication — no surprises. But two operators tend to confuse beginners at first glance, and they’re also two of the most practically useful once you understand what they actually do. The first is // — integer division. Instead of returning a precise decimal result, it divides and discards everything after the decimal point: 17 // 5 → 3 Not 3.4. Just 3. The remainder is ignored entirely. The second is % — the modulo operator. It returns exactly what // discards — the remainder after division: 17 % 5 → 2 Together, they give you complete control over how a number divides. And that turns out to be useful in situations that don’t look like math problems at first. The clearest example is time conversion. If a program receives a duration in seconds — say, 7383 seconds — and needs to display it in hours, minutes, and seconds: total_seconds = 7383 hours = total_seconds // 3600 remaining = total_seconds % 3600 minutes = remaining // 60 seconds = remaining % 60 print(f"{hours}h {minutes}m {seconds}s") → 2h 3m 3s No libraries. No external tools. Just two operators applied in sequence, each doing a precise job. The same pattern appears in pagination — calculating how many full pages a dataset fills and how many items remain on the last one. Or in determining whether a number is even or odd, where n % 2 == 0 is one of the most common checks in programming. What makes // and % worth studying carefully isn’t their complexity — it’s how often a problem that looks complicated turns out to have a clean solution once you think in terms of division and remainder. #Python #PythonMOOC2026 #BackendDevelopment #SoftwareEngineering #LearningInPublic #UniversityOfHelsinki
To view or add a comment, sign in
-
-
So I have been leveling up with boot.dev learning python. To this point it has been really simple. Just learning more about variables, something that I really know. However something I just did made me stop to think. Assignment: We need to reduce our hero's health as they take damage. Before each print() function in the provided code, change the value of player_health to 100 less than it was before. The final output should look like this: 900 800 700 600 My line of code player_health = 1000 # reduce by 100 here print(player_health-100) # and here print(player_health-200) # and here print(player_health-300) # and here print(player_health-400) Their line of code player_health = 1000 # reduce by 100 here player_health = 900 print(player_health) # and here player_health = 800 print(player_health) # and here player_health = 700 print(player_health) # and here player_health = 600 print(player_health) I got the correct output however this was always my delima with math. I can overthink and tend to find other ways to "skin the cat," not sure if this is going to continue to give me the output I will need but we will see.
To view or add a comment, sign in
-
🚀 Day 6: Mastering the Logic of Python | Flow Control Python isn't just about writing code; it's about making decisions. Today was all about Flow Control Statements—the "logical backbone" that transforms a script into an intelligent program. In my latest session, I dived deep into how Python decides how and when code blocks execute. Here’s a breakdown of the Day 6 deep dive: 🧠 The Decision Engine: Conditional Statements I explored how to guide program execution through branching paths: if, if-else, and if-elif-else: Handling everything from simple checks to complex, multi-layered grading systems. match-case (Python 3.10+): A cleaner, more readable "multi-way" decision-maker that feels like a modern switch-case. 🔄 The Engine of Efficiency: Looping Statements Iteration is where the power lies. I practiced: for & while loops: Repeating operations until conditions are met. Loop-Else: A unique Python feature where the else block executes only if the loop finishes normally (without a break). Nested Loops: Essential for processing complex data like matrices and patterns. 🚦 Fine-Tuning Control: Transfer Statements Knowing when to exit or skip is just as important as knowing when to run: break: Immediate exit from a loop. continue: Skipping the current iteration to move to the next. pass: The ultimate "placeholder" that does nothing but keep the syntax valid. 🛠️ Hands-On Logic Building I applied these concepts to solve real-world logic problems: ✅ Finding the biggest of three numbers using nested if..else. ✅ Building a Digit-to-Word converter. ✅ Mathematical validation: Prime Number and Perfect Number checks. ✅ String Reversal logic using both for and while loops. A huge shoutout to my mentor Nallagoni Omkar Sir for emphasizing that it's not just about syntax—it's about clarity, edge cases, and real-world logic. Next Stop: Functions! 🚀 #Python #CorePython #FlowControl #DataScience #LearningInPublic #CodingJourney #PythonProgramming #LogicBuilding #TechCommunity
To view or add a comment, sign in
-
I started learning Python recently, and what struck me first wasn’t the syntax, it was the thinking. Variables felt simple at first, until I realized they’re not just containers, they’re decisions. What you name, what you store, and how you structure it all reflects how clearly you understand a problem. Then came data structures,lists, dictionaries, tuples. At a glance, they look like tools. But in practice, they shape how you organize the world you’re trying to analyze. I’m beginning to see that Python isn’t just about writing code, it’s about learning how to think in systems, patterns, and relationships. Still early in the journey, but already asking better questions than I did yesterday,and that feels like progress. For those further ahead: What concept in Python changed the way you think, not just the way you code?
To view or add a comment, sign in
-
-
Python: 05 🐍 Python Iterables: Diving Deeper 🚀 We'll work on different complex types (range, list etc.) and strings iteration. We've already known the for loops, now let's dive into deeper and know what is range function returns. 🔍 We will use a built in 'type' function to get the type of an object. 🛠️ For example: type(5) .. it will return <class 'int'>; that means number 5 is an integer value 🔢 type(range(5)) .. it will return <class 'range'>; that means we get the value from a range function that means its an object of type range! 🧊 Primitive vs. Complex Types 💡 In python we have primitive types like numbers, strings, Booleans. We also have so many complex types, 'range' is one of those complex types. So interesting concept of range is, it is iterable which means we can iterate over it or use it in a for loop. That is why we can write code like this: for x in range(3): Here x can hold number in the range in each iteration. 🔄 Result: 1 2 3 Strings are also iterable! 🧵 For example: for x in "python": print(x) It will return: ✨ p ✨ y ✨ t ✨ h ✨ o ✨ n Which means x will hold one character from the string in each iteration. 🔡 List Iteration 📋: for x in [1, 2, 3, 4,..,n]: print(x) It will return: 1 2 3 4 ... ... ... nth X will hold one object from the list in each iteration. 🎯 #PythonProgramming #PythonDeveloper #Coding #python #iterator #DataScience #pythondeveloper #programmer
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