Exploring Python Context Managers under the hood Context managers are one of Python's most powerful features for resource management. I’ve been diving into how the context protocol works, and it’s fascinating to see how the with statement actually operates. To implement a context manager from scratch, you need two dunder methods: __enter__: Sets up the environment. If you’re opening a file or a database connection, this method prepares the object and returns it. __exit__: Handles the cleanup. It ensures that regardless of whether the code succeeds or crashes, the resources (like file handles or network sockets) are properly closed. As a fun experiment, I wrote this helper class to redirect print statements to a log file instead of the console: import sys class MockPrint: def __enter__(self): # Store the original write method to restore it later self.old_write = sys.stdout.write self.file = open('log.txt', 'a', encoding='utf-8') # Redirect stdout.write to our file logic sys.stdout.write = self.file.write return self def __exit__(self, exc_type, exc_value, traceback): # Restore the original functionality and close the file sys.stdout.write = self.old_write self.file.close() # Usage with MockPrint(): print("This goes to log.txt instead of the console!") While Python’s standard library has tools like contextlib.redirect_stdout for this exact purpose, building it manually really helped me understand how the protocol manages state and teardown. It’s a simple concept, but it's exactly what makes Python code so clean and safe. #Python #SoftwareEngineering #Backend
Python Context Managers Explained
More Relevant Posts
-
Ever wondered how Python knows what to do when you use + between two objects? Or how len() works on your custom class? The answer lies in magic methods (also called dunder methods). These are special methods wrapped in double underscores, and they're what make Python feel like magic. Here are a few that changed how I write code: __init__ — The constructor everyone knows. But it's just the beginning. __repr__ & __str__ — Control how your object looks when printed or logged. Debugging becomes 10x easier when your objects speak for themselves. __len__, __getitem__, __iter__ — Make your custom class behave like a built-in list or dictionary. Your teammates won't even know the difference. __enter__ & __exit__ — Power behind the with statement. Perfect for managing resources like files, DB connections, and locks. __eq__, __lt__, __gt__ — Define what "equal" or "greater than" means for your objects. Sorting a list of custom objects? No problem. __call__ — Make an instance callable like a function. This one unlocks some seriously clean design patterns. The real power of magic methods isn't just the syntax — it's that they let you write intuitive, Pythonic APIs that feel native to the language. When your custom class supports len(), iteration, and comparison naturally, your code becomes easier to read, test, and maintain. What's your favorite magic method? Drop it in the comments #Python #SoftwareEngineering #Programming #PythonTips #CleanCode #BackendDevelopment
To view or add a comment, sign in
-
-
💡 Python Control Flow with "try/except", "continue", and "break" Here’s an interesting Python snippet that combines exception handling with loop control statements: x = 0 for i in range(5): try: if i == 1: raise ValueError if i == 3: continue if i == 4: break x += i except ValueError: x += 10 print(x) 🔎 Key concepts demonstrated in this example: • "raise ValueError" triggers an exception intentionally when "i == 1", which moves execution to the "except" block and adds 10 to "x". • "continue" skips the remaining code in the current iteration (so "x += i" is not executed when "i == 3"). • "break" terminates the loop completely when "i == 4". • The "try/except" block ensures the program continues running even when an exception occurs. 📊 Step-by-step result: - "i = 0" → "x = 0" - "i = 1" → exception → "x += 10" → "x = 10" - "i = 2" → "x += 2" → "x = 12" - "i = 3" → "continue" → no change - "i = 4" → "break" → loop stops ✅ Final output: 12 Understanding how exception handling interacts with loop control statements is a powerful skill when writing robust Python code. #Python #Programming #AI #DataScience #100DaysOfCode #Analytics #Instant #LearningInPublic
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
-
-
𝗦𝘁𝗼𝗽 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻 𝗟𝗶𝗸𝗲 𝗮 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿 — 𝗗𝗼 𝗧𝗵𝗶𝘀 𝗜𝗻𝘀𝘁𝗲𝗮𝗱 I see this in code frequently. 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘄𝗵𝗼 𝗸𝗻𝗼𝘄 𝗣𝘆𝘁𝗵𝗼𝗻 𝗯𝘂𝘁 𝗮𝗿𝗲𝗻'𝘁 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻𝗶𝗰 𝗰𝗼𝗱𝗲. There's a difference between code that works and code that belongs in Python. Look at the two examples in the image. 𝗦𝗮𝗺𝗲 𝗼𝘂𝘁𝗽𝘂𝘁. 𝗕𝘂𝘁 𝗼𝗻𝗲 𝗿𝗲𝗮𝗱𝘀 𝗹𝗶𝗸𝗲 𝗮 𝘁𝗿𝗮𝗻𝘀𝗹𝗮𝘁𝗲𝗱 𝗖 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. The other reads like Python. Here are the patterns I see developers overuse and what to do instead: ❌ Manual index loops → ✅ enumerate() ❌ Building lists with .append() in loops → ✅ list comprehensions ❌ Checking "if len(x) > 0" → ✅ just "if x" ❌ Manual min/max logic → ✅ built-in min(), max() with key= ❌ Catching bare Exception → ✅ catch specific exceptions 𝗡𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 𝗮𝗿𝗲 𝗮𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗣𝘆𝘁𝗵𝗼𝗻. They're just Python being Python. When I started, I wrote Python like I was still thinking in C. It took real project work like building actual APIs and handling real data before these patterns became instinct. The shift happens when you stop learning syntax and start reading great Python code written by others. 𝗪𝗵𝗶𝗰𝗵 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 '𝗯𝗲𝗴𝗶𝗻𝗻𝗲𝗿 𝘁𝗿𝗮𝗽𝘀' 𝗱𝗶𝗱 𝘆𝗼𝘂 𝗳𝗮𝗹𝗹 𝗶𝗻𝘁𝗼 𝘁𝗵𝗲 𝗹𝗼𝗻𝗴𝗲𝘀𝘁 𝗯𝗲𝗳𝗼𝗿𝗲 𝗳𝗶𝗻𝗮𝗹𝗹𝘆 𝗯𝗿𝗲𝗮𝗸𝗶𝗻𝗴 𝘁𝗵𝗲 𝗵𝗮𝗯𝗶𝘁? #Python #PythonTips #CleanCode #BackendDevelopment #LearnPython #SoftwareEngineering
To view or add a comment, sign in
-
-
🧠 Python Concept That Runs When Class Is Called: __call__ on Classes Objects can be callable… but classes can customize calls too 👀 🤔 The Surprise When you do: obj = MyClass() Python actually does: obj = MyClass.__call__() 🧪 Example class Logger: def __call__(self, msg): print("LOG:", msg) log = Logger() log("Hello") 🎯 Class instances become functions 🧠 But Classes Themselves Use __call__ class Meta(type): def __call__(cls, *args, **kwargs): print("Creating instance") return super().__call__(*args, **kwargs) class User(metaclass=Meta): pass u = User() ✅ Output Creating instance Metaclass intercepted construction. 🧒 Simple Explanation 🥤 Imagine a vending machine 🥤 Press button → machine runs → gives item 🥤 That press = __call__. 💡 Why This Is Powerful ✔ Factories ✔ Dependency injection ✔ Framework hooks ✔ Callable objects ✔ Advanced APIs ⚡ Real Uses 💻 PyTorch modules 💻 FastAPI dependencies 💻 Decorator classes 💻 DSL builders 🐍 In Python, calling isn’t just for functions 🐍 Classes and objects can redefine what “()” means. 🐍 __call__ is the hook behind that power. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 Python Concept That Controls Attribute Access: __getattribute__ vs __getattr__ They sound similar… but behave very differently 👀 🤔 The Difference 💻 __getattribute__ → runs for every attribute access 💻 __getattr__ → runs only if attribute not found 🧪 Example class Demo: def __getattribute__(self, name): print("getattribute:", name) return super().__getattribute__(name) def __getattr__(self, name): print("getattr:", name) return "default" d = Demo() d.x = 10 print(d.x) print(d.y) ✅ Output getattribute: x 10 getattribute: y getattr: y default 🧒 Simple Explanation Imagine asking your mom for things 👩 💻 __getattribute__ → mom checks every request 💻 __getattr__ → mom answers only if not found 💡 Why This Is Powerful ✔ Lazy attributes ✔ Proxies & wrappers ✔ Debugging tools ✔ Framework internals ⚠️ Important Rule Inside __getattribute__ always call: super().__getattribute__(name) Otherwise → infinite recursion 😬 🐍 Python lets you intercept attribute access itself 🐍 Understanding __getattribute__ vs __getattr__ unlocks advanced OOP patterns. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Day 9: Mastering Type Casting in Python 🐍 Today I explored how Python handles type conversions, and it's more powerful than I initially thought! Type casting lets us convert data from one type to another, which is essential when working with user inputs, APIs, or databases. Key takeaways: Implicit vs Explicit Casting: Python automatically converts some types (like int to float), but we often need to explicitly cast data using functions like int(), str(), float(), and bool(). Real-world scenario: Converting user input (always a string) into integers for calculations, or formatting numbers as strings for display. Common pitfalls I learned to avoid: Not every string can be cast to an integer, and float to int conversion truncates decimals rather than rounding. Code snippet from today: python # User age input age = int(input("Enter your age: ")) # Converting for display price = 49.99 print(f"Price: ${str(price)}") # List to string items = ['apple', 'banana', 'cherry'] print(', '.join(items)) The journey continues! Each day brings new understanding of how Python handles data behind the scenes. #Python #FullStackDevelopment #CodingJourney #100DaysOfCode #LearningToCode #WebDevelopment
To view or add a comment, sign in
-
-
Python Portal: Use itertools instead of loops While loops are great, they have limitations, especially in modern programming styles and for certain types of problems. Understanding these limitations helps you choose the right tool for the task. Each loop iteration in Python incurs interpreter overhead, such as type checking and memory management. This can add up significantly on large datasets. To get around this limitation, Python has a convenient built-in library, itertools. For example, suppose you need to generate all unique pairs from a given list. Order is unimportant, and no element should be paired with itself. To avoid code bloat and reduce the risk of bugs, you can use the itertools library. The itertools.combinations() function directly generates all unique combinations of elements from an iterable, without repetition or order. Here's how you can rewrite the code using combinations from itertools: from itertools import combinations def get_unique_pairs_itertools(items): return list(combinations(items, 2)) my_list = ['A', 'B', 'C', 'D'] print(get_unique_pairs_itertools(my_list)) Output: [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')] Original: https://lnkd.in/dRUUNewb
To view or add a comment, sign in
-
Most of us write Python without thinking about what's happening under the hood. But understanding memory management can be the difference between a script that scales. Here's what every Python developer should know: Python handles memory automatically — but not magically. CPython uses reference counting as its primary mechanism. Every object tracks how many references point to it. When that count hits zero, the memory is freed. Simple, elegant, and mostly invisible. But reference counting has a blind spot: circular references. If object A references B and B references A, neither count ever reaches zero. That's where Python's cyclic garbage collector steps in — it periodically detects and cleans up these cycles. Practical tips I've learned the hard way: → Use del to explicitly remove references you no longer need in long-running processes → Be careful with large objects in global scope — they live for the entire program lifetime → Use generators instead of lists when processing large datasets — they're lazy and memory-efficient → Profile before optimizing. Tools like tracemalloc, memory_profiler, and objgraph are your best friends → Watch out for closures accidentally holding onto large objects The bigger picture: Python's memory model is designed to let you focus on solving problems, not managing pointers. But when you're building data pipelines, web services, or ML workflows at scale, knowing these internals pays dividends. What memory-related bugs have caught you off guard in Python? Drop them in the comments #Python #SoftwareEngineering #Programming #BackendDevelopment #PythonTips
To view or add a comment, sign in
-
-
In Part 1, we saw packets flow through the kernel into socket buffers. Now let's see what Python does with them. Published Part 2, covering how asyncio and ASGI actually work under the hood. How the event loop uses epoll to monitor thousands of sockets, what happens when you await, how Uvicorn bridges bytes to FastAPI, and why async scales so well. The best part? Seeing how it all connects. The kernel work sets up everything for asyncio to handle massive concurrency with minimal overhead. https://lnkd.in/gcTm9fyB #Python #FastAPI #asyncio #HTTP #ASGI
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