Why Python prefers 𝘵𝘳𝘺 / 𝘦𝘹𝘤𝘦𝘱𝘵 over 𝘪𝘧 𝘦𝘭𝘴𝘦 checks? TL;DR: In Python, exceptions are part of normal flow, not rare events! There are two ways to walk through a uncertain code block - 1. Look Before You Leap (LBYL) - - Check conditions before doing the action - The 𝘪𝘧 𝘦𝘭𝘴𝘦 statements. - But here, Python looks at the dictionary twice. Once to check if the key exists, and once to actually fetch it. 2. Easier to Ask Forgiveness than Permission (EAFP) - Assume things will work and wrap the action in a try block. - If the key exists (which is usually the case), execution stays on the fast path. EAFP is the "Pythonic" approach. It is the way Python is built internally too. Python uses exceptions internally for everything. When using a for loop, Python doesn't check the length of the list; it just keeps asking for items until the list raises a StopIteration exception. Takeaway - -> Using try excepts will not add to any extra processing time, if not reduce it in most of the practical cases. -> Use LBYL if the failure is expected to happen often. -> Use EAFP if the failure is unexpected and rare. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
Python's EAFP Approach: Why Exceptions are Preferred
More Relevant Posts
-
Day 26 | Python Tricks Beginners Don’t Know 🐍 When I started Python, I thought writing longer code meant better code. Turns out… smarter Python is often shorter. Here are a few simple tricks that changed how I write code: 1️⃣ Multiple Assignment Instead of: a = 5 b = 10 You can write: a, b = 5, 10 2️⃣ Swapping Variables (Without Temp Variable) Instead of: temp = a a = b b = temp Just write: a, b = b, a 3️⃣ Using enumerate() Instead of Manual Indexing Instead of: for i in range(len(items)): print(i, items[i]) Use: for index, value in enumerate(items): print(index, value) Cleaner. More readable. More Pythonic. Python isn’t about writing more code. It’s about writing clear, efficient code. Which Python trick surprised you when you learned it? #Day26 #PythonLearning #PythonTips #CodingJourney #AIJourney #DataScienceStudent #LearningInPublic #TechGrowth
To view or add a comment, sign in
-
🚀 Day 6/30 – Python OOPs Challenge 💡 Types of Methods in Python Class In Day 5, we learned about instance methods. Today let’s see all main types of methods in Python. 🔹 There are 3 types of methods: 1️⃣ Instance Method 2️⃣ Class Method 3️⃣ Static Method 🔹 1. Instance Method - Works with object data - Uses self 🔹 2. Class Method - Works with class data - Uses cls - Defined using @classmethod 🔹 3. Static Method - Does not use object or class data - Defined using @staticmethod 🔹 Simple Example: ``` class Student: college = "ABC College" def __init__(self, name): self.name = name def show_name(self): # Instance method print(self.name) @classmethod def show_college(cls): # Class method print(cls.college) @staticmethod def greet(): # Static method print("Welcome to the class") s1 = Student("Argha") s1.show_name() Student.show_college() Student.greet() ``` 🔹 When to use what? - Instance method → object-specific work - Class method → class-level data - Static method → utility / helper logic 📌 Key takeaway: Python supports multiple method types for clean design. 👉 Day 7: Real-world OOP example (coming tomorrow) 👍 Like | 💬 Comment | 🔁 Share 📍 Follow me to learn Python OOP step by step #Python #OOP #LearningInPublic #30DaysOfPython #CodingJourney
To view or add a comment, sign in
-
Day 11 – Python Functions: Returns, Callbacks, Lambda & Recursion Today’s focus was on going deeper into Python functions and understanding how flexible and powerful they really are. What I learned and practiced today: How return works in functions Any code written after return is ignored A function can return values and also be printed when called Difference between: Calling a function Assigning a function to a variable and calling it later Functions are first-class objects in Python, which means: A function can be assigned to a variable Stored inside data structures like lists and tuples Passed as an argument to another function (callback function) Returned from another function (higher-order function) Higher-Order & Callback Functions: A function that takes another function as an argument is a higher-order function A function passed as an argument is called a callback function Practiced executing functions stored inside a list Anonymous (Lambda) Functions: Learned how to define functions without a name using lambda Practiced: Lambda without parameters Lambda with single and multiple parameters Default values in lambda *args and **kwargs with lambda functions Recursion Concepts: A function calling itself based on a condition is called recursion Understood: Base condition to stop recursion Memory usage concerns with recursion Why loops are often preferred over recursion Implemented: Printing numbers using recursion Printing ranges using recursion Problem-Solving with Functions: Multiplication table using a function Printing numbers in a given range Prepared tasks for: Practicing all function types with syntax and examples Re-implementing previous problems using functions Using both user-defined and predefined functions Day by day, my understanding of Python is getting stronger, especially around functional concepts and code reusability. #Python #PythonFunctions #LambdaFunctions #Recursion #HigherOrderFunctions #CallbackFunctions #ProgrammingBasics #LearningPython #DailyLearning #StudentDeveloper
To view or add a comment, sign in
-
🚀 Day 17/30 – Python OOPs Challenge 💡 Method Overloading in Python In some languages (like Java), we can create multiple methods with the same name but different parameters. That is called Method Overloading. But what about Python? 🤔 🔹 Important: Python does NOT support traditional method overloading directly. If we write: ``` class Test: def show(self): print("First") def show(self): print("Second") ``` Only the second method will work. Output: Second The first one gets overwritten. 🔹 So how do we achieve overloading in Python? We use: - Default arguments - Variable-length arguments (*args) 🔹 Example using default arguments: ``` class Calculator: def add(self, a, b=0, c=0): print(a + b + c) c1 = Calculator() c1.add(5) c1.add(5, 10) c1.add(5, 10, 15) ``` 🔹 What happened here? Same method name → different number of arguments → works fine. This is how Python handles method overloading. 📌 Key takeaway: Python achieves method overloading using *default arguments or args. 👉 Day 18: Abstraction in Python (coming tomorrow) 👍 Like | 💬 Comment | 🔁 Share 📍 Follow me to learn Python OOP step by step #Python #OOP #LearningInPublic #30DaysOfPython #CodingJourney
To view or add a comment, sign in
-
I’ve worked with Python for a few years, and variables are at the core of every program. I knew the rules like using deepcopy when copying a list but for a long time, the why behind them eluded me. Recently, I decided to take a deeper dive into Python’s internals, and everything started to click. That exploration inspired me to write a short article explaining how variables really work and why those rules exist. If you’ve ever wondered why Python behaves the way it does, I hope this is useful. https://lnkd.in/e9xNMmhf
To view or add a comment, sign in
-
🚀 Revisiting Python Fundamentals Day 6: Flow Control Statements in Python In Python, code normally executes line by line from top to bottom. But real-world programs need more than that. They need to: Make decisions Repeat actions Control execution flow That’s where Flow Control Statements come in. Flow control statements decide which block of code runs and how many times it runs. They are mainly divided into three categories: 🔹 1️⃣ Decision Statements These are used when a program needs to choose between alternatives. Python provides: if elif else Example: age = 18 if age >= 18: print("Eligible to vote") else: print("Not eligible") Here: Python checks the condition age >= 18 If it is True, the first block runs If False, the else block runs Decision statements allow programs to behave differently based on conditions. 🔹 2️⃣ Looping Statements Loops are used when a block of code needs to run multiple times. Python provides: for while For Loop Used when the number of iterations is known. for i in range(3): print(i) This prints values from 0 to 2. While Loop Used when execution depends on a condition. count = 0 while count < 3: print(count) count += 1 The loop runs until the condition becomes False. Loops reduce repetition and make programs efficient. 🔹 3️⃣ Control Statements These are used inside loops to change their normal behavior. break → immediately exits the loop continue → skips the current iteration pass → placeholder that does nothing Example using break: for i in range(5): if i == 3: break print(i) The loop stops when i becomes 3. #Python #FlowControl #PythonBasics #LearnPython #Programming
To view or add a comment, sign in
-
-
A few people have emailed me to ask how to convert Excel financial models to Python, so wrote some notes up here about how to do this with Claude - and also the benefits of doing this: https://lnkd.in/d5zuztEq
To view or add a comment, sign in
-
🚀 Day 16/30 – Python OOPs Challenge 💡 Operator Overloading in Python We learned that polymorphism means: 👉 Same name 👉 Different behaviour Today we’ll see how Python allows operators to behave differently. This is called Operator Overloading. 🔹 What is Operator Overloading? In Python: - + adds numbers - + also joins strings Same operator → different behaviour. We can also define how operators work for our own classes. 🔹 Example: ``` class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def display(self): print(self.x, self.y) p1 = Point(2, 3) p2 = Point(4, 5) p3 = p1 + p2 # Using overloaded + operator p3.display() ``` 🔹 What happened here? - We defined __add__() method - Now + works for Point objects - Python calls __add__() automatically 📌 Key takeaway: Special methods like __add__() allow operator overloading. 👉 Day 17: Method Overloading concept in Python (coming tomorrow) 👍 Like | 💬 Comment | 🔁 Share 📍 Follow me to learn Python OOP step by step #Python #OOP #LearningInPublic #30DaysOfPython #CodingJourney
To view or add a comment, sign in
-
🐍 Python Secretly Reuses Numbers — Here's Why That's Genius Most Python beginners assume that writing x = 42 and y = 42 creates two separate values in memory. They don't. Python actually pre-creates integers from -5 𝙩𝙤 256 at startup and reuses the same object every time. This is called 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 𝗜𝗻𝘁𝗲𝗿𝗻𝗶𝗻𝗴 — and it's one of Python's smartest internal optimizations. Here's what's happening under the hood: ▶ x = 42 and y = 42 both point to the exact same object in memory ▶ x is y returns True (same memory address) ▶ But x = 1000 and y = 1000 → x is y returns False (two separate objects) Why does Python do this? ✅ Memory Efficiency — Small integers like 0, 1, 2 appear millions of times in any program (loop counters, indices, comparisons). Reusing one object instead of creating millions saves significant memory. ✅ It's Safe — Integers in Python are immutable. They can never be changed after creation. So sharing the same object across multiple variables is perfectly risk-free. The key distinction every developer must know: == checks if two variables have the same VALUE is checks if two variables point to the same OBJECT in memory In real code, always use == to compare values. Relying on is for number comparison is fragile and considered bad practice — because interning is an internal Python detail, not a guarantee. You may never need to use this directly in your code. But understanding it gives you a deeper mental model of how Python manages memory — and that clarity always makes you a better programmer. #Python #Programming #SoftwareDevelopment #CodingTips #LearnPython #PythonDeveloper #TechEducation #ComputerScience
To view or add a comment, sign in
-
🧠 Python Concept That Explains Class Namespaces: __prepare__ in Metaclasses Before a class is created… Python prepares its namespace 👀 🤔 What Is __prepare__? When Python executes: class MyClass: x = 1 y = 2 It first asks the metaclass: 👉 “What mapping should I use to store attributes?” That hook = __prepare__. 🧪 Example class OrderedMeta(type): @classmethod def __prepare__(mcls, name, bases): return {} def __new__(mcls, name, bases, namespace): print(list(namespace.keys())) return super().__new__(mcls, name, bases, namespace) class Demo(metaclass=OrderedMeta): a = 1 b = 2 c = 3 ✅ Output ['a', 'b', 'c'] Metaclass saw class body order 🎯 🧒 Simple Explanation 🧸 Before kids put toys in a box, teacher chooses the box. 🧸 That box = namespace. 🧸 Choice = __prepare__. 💡 Why This Matters ✔ Ordered class attributes ✔ DSLs & frameworks ✔ Enum internals ✔ ORM field order ✔ Metaprogramming ⚡ Real Uses 💻 Enum preserves order 💻 Dataclasses fields 💻 ORM column order 💻 Serialization frameworks 🐍 In Python, even class bodies have a setup phase 🐍 __prepare__ decides how attributes are collected, before the class even exists. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
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