Day 27/50: The Circular Reference That Never Died The Setup:- Cache object holds reference to user, user holds reference back to cache. Memory grows indefinitely. The Problem:- Circular references prevent garbage collection: --- python class Cache: def __init__(self): self.users = {} user = User() cache = Cache() cache.users['user1'] = user user.cache = cache # Circular! --- Both objects stay in memory forever, even after going out of scope. The Investigation:- Memory profiler showed objects stuck in unreachable cycles. Python's garbage collector finds cycles occasionally, but not immediately. The Solution:- Used weak references to break the cycle: --- python import weakref class Cache: def __init__(self): self.users = {} user = User() cache = Cache() cache.users['user1'] = user user.cache = weakref.ref(cache) # Weak reference! # Access: cache_obj = user.cache() # Returns None if cache was garbage collected --- -> Memory stabilized. The Lesson:- Circular references are invisible memory leaks. Use weak references to break cycles in caches and callback chains. `Have you debugged circular references?` #Day27 #50DaysOfDebugging #Python #MemoryLeak #GarbageCollection #Performance #SoftwareEngineering #Debugging
Saiteja Singirikonda’s Post
More Relevant Posts
-
📅 Day 96 Summary: K Closest Points to Origin On Day 96, you successfully solved a medium-difficulty problem titled "K Closest Points to Origin" on GeeksforGeeks. 🎯 Problem Statement Goal: Given an array of points [x, y] and an integer K, return the K closest points to the origin (0,0). 🧠 Solution Approach (Max Heap / Priority Queue) The visible Python code indicates you used a Max Heap (specifically, Python's heapq module combined with negative values to simulate a Max Heap) to maintain the K closest points found so far. Calculate Squared Distance: A helper function squaredDis calculates x2 +y2 for each point. Maintain a Max Heap of Size K: The loop iterates through all points in the input. For each point, it pushes the pair (−distance,point) onto the maxHeap. The negative distance is used because Python's heapq is a Min Heap, and negating the value makes it behave like a Max Heap based on magnitude (the largest negative number is the smallest value, so the point with the largest distance among the K is at the top). If the heap size exceeds K, the element at the top (which is the point with the largest distance among the current K points) is removed using heappop. Final Result: After processing all points, the heap contains the K points with the smallest distances. The final step is to pop all elements from the heap and extract the point coordinates.
To view or add a comment, sign in
-
-
🚀 LaNet-vi is back — now in Python! LaNet-vi (Large Network Visualization), originally by José Ignacio Alvarez-Hamelin & Mariano Beiró, is a fantastic tool for exploring large graphs. A few weeks ago, I wanted to visualize the evolution of the AS-level Internet graph, but the C++ build + deps made it challenging, so I ported it to Python. 🧠 What’s k-core decomposition (the heart of LaNet-vi)? It “peels” the network by iteratively removing nodes with degree < k, revealing nested k-shells. These shells form tiers, a natural hierarchy from the sparse periphery (low k) into increasingly dense cores (high k). LaNet-vi visualizes these tiers so you can see the Internet’s structural backbone at a glance. What’s new 🐍 Pure-Python reimplementation using networkx, matplotlib, and pandas ⚡ Modern dependency management with uv 📥 Broader input formats support 🧯 More robust error handling + structured logging 🔓 Open repo for issues & contributions — and a PyPI release Links GitHub: https://lnkd.in/dhT7ssT2 PyPI: https://lnkd.in/dgKnXB3i 💡 Demo: AS-level Internet graph rendered with CAIDA’s October 2025 AS-relationship dataset. If this is useful, please ⭐ the repo and open issues/PRs — feedback welcome! #Python #OpenSource #NetworkScience #Visualization #InternetTopology #NetworkX #Matplotlib
To view or add a comment, sign in
-
-
Day 14 #45Days_of_learning #Exception_handling Exception handling is a mechanism that allows your program to respond to runtime errors (exceptions). It handles the errors by exception so that the program flow can continue normally. Python provides #five keywords for exception handling: #try in try block we write the exception code. #except we need to place the code to handle errors(message gives to users). #else to run code only when no error occurs. #finally used for cleanup actions. gives the result of try block. #raise choose to throw an exception if a condition occurs. #example try: x = int(input("Enter a number: ")) result = 10 / x print("Result is:", result) except ZeroDivisionError: print("Error: You cannot divide by zero!") except ValueError: print("Error: Please enter a valid number.") else: print("Great! No errors occurred.") finally: print("Program execution completed.") #output: 0 Enter a number: 0 ERROR! Error: You cannot divide by zero! Program execution completed. #output: 1.2 Enter a number: 1.2 ERROR! Error: Please enter a valid number. Program execution completed. #output:20 Enter a number: 20 Result is: 0.5 Great! No errors occurred. Program execution completed.
To view or add a comment, sign in
-
🗓️ Python Daily – Day #1 🎯 Topic: Mastering List Comprehensions 🔥 💡 Concept: Transforming lists in one elegant line! List comprehensions let you create new lists by applying an expression to each item in an iterable — cleaner and faster than regular loops. \*\*Example:\*\* Create a list of squares for numbers 1 through 5. ```python squares = \[x\*\*2 for x in range\(1, 6\)\] print\(squares\) # Output: \[1, 4, 9, 16, 25\] ``` \*\*Quiz:\*\* Write a list comprehension to create a list of even numbers between 1 and 20 \(inclusive\). ✅ Hint: Use a condition inside the comprehension to filter even numbers. 🧩 Answer: ```python evens = \[x for x in range\(1, 21\) if x % 2 == 0\] print\(evens\) # \[2, 4, 6, 8, 10, 12, 14, 16, 18, 20\] ```
To view or add a comment, sign in
-
69. Sqrt(x) Solved Easy Topics Companies Hint Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. Example 1: Input: x = 4 Output: 2 Explanation: The square root of 4 is 2, so we return 2. Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
To view or add a comment, sign in
-
-
🚀 𝐏𝐲𝐭𝐡𝐨𝐧 𝟑.𝟏𝟒 - 𝐓𝐡𝐞 𝐧𝐞𝐰 𝐅𝐫𝐞𝐞-𝐓𝐡𝐫𝐞𝐚𝐝𝐢𝐧𝐠 𝐦𝐨𝐝𝐞𝐥 𝐚𝐧𝐝 𝐰𝐡𝐲 𝐢𝐭 𝐦𝐚𝐭𝐭𝐞𝐫𝐬 🚀 If you’ve been writing Python for a while, you’ve probably bumped into the limitations of the Global Interpreter Lock (GIL). The GIL means that even on a multi-core machine, threads in one Python process can’t execute Python bytecode truly in parallel. Only one thread runs at a time ! With Python 3.14, the “𝒇𝒓𝒆𝒆-𝒕𝒉𝒓𝒆𝒂𝒅𝒆𝒅” or “no-GIL” build is officially supported. That means you can opt-into a version of CPython where the GIL is disabled and threads can truly run in parallel across multiple CPU cores. ⚠️𝐖𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐆𝐈𝐋? In previous Python versions, the Global Interpreter Lock (GIL) ensured only one thread could really execute Python bytecode at a time, so even on multi‐core hardware, threads couldn’t fully run in parallel. 💡𝐖𝐡𝐚𝐭 𝐜𝐡𝐚𝐧𝐠𝐞𝐬 𝐰𝐢𝐭𝐡 𝐟𝐫𝐞𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐢𝐧𝐠? - Threads can now truly run in parallel on multiple cores when using a free-threaded build of Python (python3.14t) - This opens up real gains for CPU-bound, multithreaded Python workloads. - Existing Python libraries written in thread-safe way, should work without modification and utilize all cores of CPU. - C extension that has not been explicitly marked as free-thread-safe, it will re-enable the GIL for the lifetime of that process. 🔍𝐁𝐨𝐭𝐭𝐨𝐦 𝐥𝐢𝐧𝐞 If your Python apps care about multi-core performance or threading, this update is worth watching (or even experimenting with). It’s a strong signal that Python is leveling up its concurrency game, and making it easier for developers to build more scalable, high-performance systems. #Python #Python314 #Concurrency #Multithreading #GIL #SoftwareEngineering #DevCommunity
To view or add a comment, sign in
-
-
\(aiohttp & asyncio\) vs Requests: Comparing Python HTTP Libraries 1. Requests - The Simple Synchronous Library What it is: Synchronous blocking HTTP library Simple, intuitive API Most popular for basic HTTP operations Blocks execution until response is received Simple scripts Sequential API calls Learning/prototyping When performance isn't critical import requests import time # Basic GET request response = requests.get\('https://lnkd.in/gZr2tbvq) print\(response.json\(\)\) # Making multiple requests \(BLOCKING - one at a time\) def fetch\_multiple\_sync\(\): urls = \[ 'https://lnkd.in/geAKeWr3', 'https://lnkd.in/gTPFcRiG', 'https://lnkd.in/gndc7mJB' \] start = time.time\(\) results = \[\] for url in urls: response = requests.get\(url\) results.append\(response.json\(\)\) print\(f"Time taken: \{time.time\(\) - start:.2f\} seconds"\) # Output: \~3 seconds \(1 second per request, sequential\) return results # POST request with headers and data re https://lnkd.in/g9ze5V35
To view or add a comment, sign in
-
Built a quick reference guide for RAG patterns. Spent some time documenting 5 common patterns I kept seeing in production systems: • Semantic chunking • HyDE (query expansion) • Re-ranking • Metadata filtering • Query decomposition Each one has working Python code and notes on when it's worth using vs. when it's overkill. Also threw in some case studies with actual numbers ($900K-$2.3M impact range) from real implementations I researched. Nothing groundbreaking - just a clean reference for the trade-offs (latency, cost, quality) since I couldn't find one that laid it out clearly. Live docs: https://lnkd.in/edsUB5mA Code: https://lnkd.in/e9Xqrme6 #MachineLearning #RAG #Python
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