How FINALLY keyword in Python can silently change your function’s behaviour? How does the try except flow works? 1. When Python enters a try block, it pushes a "cleanup" instruction onto the stack. 2. When you hit a return statement inside try, Python doesn't actually exit the function immediately, it just "saves" the return value. 3. If you return inside the finally block itself, the original return value is discarded. More worse - This same thing happens with exceptions too. If your try block raises a error, but your finally block has a return or a break, the error vanishes! Takeaway - 1. Never use return, break, or continue inside a finally block. It can lead to "silent failures" and unexpected bugs. 2. Finally is meant only for cleanup (closing files, releasing locks) and not logic. I’m deep-diving into Python internals. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
Python Try Except Flow: Avoid Silent Failures with Finally Block
More Relevant Posts
-
Python Tip — Let Your Code Clean Up After Itself You can manage files manually with 'try/finally'. Initialize the variable. Check if it exists. Close it carefully. It works. But modern Python asks a better question: Why manage manually what the language can guarantee automatically? 'with' eliminates boilerplate, removes hidden bugs, and makes cleanup automatic. The difference isn’t syntax. It’s philosophy. Write code that protects itself. FOLLOW FOR MORE PYTHON TIPS & INSIGHTS. #Python #CleanCode #SoftwareEngineering #ProgrammingTips
To view or add a comment, sign in
-
-
Python Tip - Inheritance (issubclass() & isinstance()) Know the Smart Way to Check Your Hierarchy Inheritance is powerful, but knowing how your classes relate is what makes it truly Pythonic. Instead of manually checking types or class names, trust Python’s built-ins like issubclass() and isinstance(). They handle deep hierarchies, keep your code clean, and save you from brittle, error-prone checks. Pro Tip: Modern inheritance isn’t just about reusing code, it’s about writing robust, scalable, and readable class relationships. FOLLOW FOR MORE PYTHON TIPS & INSIGHTS #Python #OOP #CleanCode #SoftwareEngineering #Backend #ProgrammingTips
To view or add a comment, sign in
-
-
Why .join() is faster than str1 + str2 in Python? Why string concatenation gets really slow in Python? Strings are immutable in Python. When we write str1 + str2, following steps are done - 1. Request a brand new block of memory large enough for both. 2. Copy every single character from str1 and str2 into the new block. 3. Destroy the old strings (eventually) If we do this 10,000 times in a loop, we are copying millions of characters over and over again. When we use ''.join(list_of_strings), Python is significantly smarter. It performs following 2 pass operation - 1. It iterates through the entire list once to calculate the total length of the final string. 2. it allocates one single block of memory of that exact size and copies all the strings into their respective slots at once. Instead of n reallocations and n copies, one allocation and one copy! Takeaway - -> Need to join 2 or 3 strings - a + b is fine and very readable. -> Need to join strings in a loop - Always collect them in a list first and use ''.join(my_list) at the very end. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Python feels really a magic to me Today I realized something interesting about Python Most languages make you write 10 lines But in Python lets do it in 1 clean line. Examples: # swap without temp variable a, b = b, a # reverse list nums[::-1] # multiple assignment x = y = z = 0 # list in one line squares = [x*x for x in range(10)] # dictionary from two lists dict(zip(keys, values)) Lt’s like thinking smarter, not harder. #python
To view or add a comment, sign in
-
-
Day 25 | The Python Feature That Made My Code Cleaner 🐍 One small Python concept that felt confusing at first — but now I love: List Comprehensions. Earlier, I used to write: squares = [] for i in range(10): squares.append(i * i) Then I learned this: squares = [i * i for i in range(10)] Same result. Cleaner. Shorter. More readable. At first it looked complicated. Now it feels natural. That’s the thing about Python — Many concepts look hard until you understand the pattern. List comprehensions taught me: • Think in expressions • Write concise logic • Read code more efficiently Still practicing. Still improving. What Python concept took time to “click” for you? #Day25 #PythonLearning #ListComprehension #CodingJourney #AIJourney #DataScienceStudent #LearningInPublic #TechGrowth
To view or add a comment, sign in
-
When I review Python code, I often look past syntax and focus on decisions. Take this line: if user_id in users: grant_access() It works. But what matters is what users actually is. A list → Python checks items one by one A set or dict → Python jumps straight to the answer Same line of code. Very different performance. With large data, these choices decide whether a system feels instant or slow. This is the kind of detail that separates: • someone who writes Python • from someone who understands how Python behaves I recently wrote a complete breakdown of how Python searches data internally—linear search, binary search, and hash lookup—using real examples and benchmarks. It’s not about algorithms. It’s about choosing the right data structure upfront. Full breakdown 👇 https://lnkd.in/gT2uaZER #Python #SoftwareEngineering #BackendEngineering #Performance #CodeQuality
To view or add a comment, sign in
-
-
Why does a += 10 give an error, but a = 2 then a += 10 works perfectly? 🤔 I made this mistake today and learned something crucial about Python's compound assignment operators. The wrong way: a += 10 # ERROR: name 'a' is not defined ❌ The right way: a = 2 # Initialize first a += 10 # Now it works! ✅ # Result: a = 12 Here's why: Compound operators like +=, -=, *=, /= are shortcuts that perform operations AND assignment together. When you write a += 10, Python actually executes a = a + 10 To add 10 to a, Python first needs to READ the current value of a. If a doesn't exist yet, there's nothing to read — hence the error! Key takeaway: Always initialize your variable before using compound operators. It's not just syntax — it's logic. Have you encountered this error before? What was your "aha!" moment with Python operators? 💡 #Python #CompoundOperators #AssignmentOperators #PythonBasics #CodingMistakes #LearnPython #ProgrammingFundamentals
To view or add a comment, sign in
-
-
The coolest move in Python syntax: The "Moonwalk" loop. 🕺 Beginners often overcomplicate counting backwards in Python. I’ve seen clunky while loops, manually decrementing counters, or creating lists just to reverse them [::-1]. Stop working so hard. The "Pro" move is to unlock the often-ignored third parameter of the built-in range() function: the step. The syntax is: range(start, stop, step) By default, the step is positive (+1), moving you forward. But if you set the step to -1, you tell Python to slide backwards. In the visual below: Start at 10. Stop before 0 (Remember, the stop index is exclusive!). Step back by -1 each time. It’s clean, readable, and honestly, it just looks way cooler than a messy while loop. 😎 Want to learn a new Python trick every morning? We turn boring documentation into fun, bite-sized lessons. Get them delivered straight to your inbox daily. 👉 Join the PyDaily community here: https://lnkd.in/ducXvs-y #Python #CodingTips #LearnPython #SoftwareEngineering #Developer #PyDaily
To view or add a comment, sign in
-
-
🚀 New YouTube Video: Python zip() Function Explained | From Basics to Internals 🐍🔗 The zip() function looks simple, but it plays a very important role when working with multiple iterables in Python—especially in clean, efficient code. In this video, I’ve explained the Python zip() function from scratch, including: ✅ What the zip() function does ✅ How zip() works with multiple iterables ✅ How iter() and next() work behind the scenes ✅ Why zip() stops silently ✅ Common mistakes beginners make If you’re learning Python or revising core concepts, this video will help you understand zip() with clarity and confidence 💪 🎥 Watch here: 👉 https://lnkd.in/gAEpQiUW If you find it helpful, don’t forget to like, share, and subscribe 🙌 Your feedback really motivates me to create more quality content. #Python #PythonProgramming #FileHandling #LearnPython #DataAnalytics #DataScience #ProgrammingBasics #SoftwareDevelopment #Coding #YouTubeEducation #datadenwithprashant #ddwpofficial If this helped you, drop a 👍 or comment “zip” 👇
To view or add a comment, sign in
-
-
Python WTF?! Today's post is about those moments when Python makes you pause and say: "Wait… what?" I put together a small image with a few examples of… let's say, non-obvious Python behavior. > round(2.5) == round(1.5) == 2 > 0.1 + 0.2 gives 0.30000000000000004 > [[0] * 3] * 3 behaves very strangely after mutation > print(lst.sort()) prints None Everything above is valid Python. Nothing is a bug. But all of it can easily lead to silent, hard-to-notice issues in real projects. The danger is not syntax errors. The danger is thinking you know what the code does - when you actually don't. Python is friendly. But it has sharp edges. Now your turn Explain why each of these four cases behaves this way. Let's see who truly understands what's going on under the hood. #python #sort #float #round #wtf
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
Great insight Onkar!