Hello Everyone, Welcome to my ongoing decoding Python Magic Series today i want to talk about destroying resources in Python.

__del__

__del__ used for object destruction or cleanup. It’s called when an object is about to be destroyed, typically when it goes out of scope or explicitly deletes it using the del keyword.

def __del__(self):
# Cleanup codeResource Cleanup

__del__ can be used to release external resources like file handles, network connections, or database connections when an object is destroyed.

class FileHandler:
def __init__(self, filename):
print(f”Opening {filename}”)
self.filename = filename
self.f = open(filename, ‘r’)

def __del__(self):
print(“Closing file %s” % (self.filename))
self.f.close()

def read_file():
fh = FileHandler(“./file.py”)
print(fh.f.readlines())

read_file()Opening ./file.py
[‘import mathn’]Closing file ./file.pyPython garbage collection calls __del__ to remove variables from scope.

Context Manager are the ideal way to be used for managing resource like these.

Decoding Python Magic : __enter__ and __exit__

Custom Cleanup Logic

If an object needs special cleanup logic beyond what’s provided by Python’s garbage collector, __del__ can be used.

class CustomClean:
def __init__(self):
self.data = [1, 2, 3]

def __del__(self):
self.data.clear()

def fn():
cc = CustomClean()Deleting Keys and indexes from dict and listl = [1, 2, 3]d = {“a”: [1, 2, 3], “b”: set([1, 2, 3])}

del l[0]del d[“a”]

print(l)
print(d)

# [2, 3]# {‘b’: {1, 2, 3}}

Limitation and Alternatives

Unreliable Timing: The timing of __del__ invocation is not guaranteed. It may not be called immediately when the object is no longer needed, which can lead to resource leaks.Circular References: __del__ doesn’t handle circular references well, potentially causing memory leaks. The weakref module can be used for handling such cases.Finalization: For reliable cleanup, context managers (with statement) or explicit cleanup methods are recommended over __del__. Context managers ensure cleanup regardless of exceptions.Weak References: For dealing with circular references, the weakref module provides a better alternative. It allows the creation of weak references to objects, which won’t prevent them from being garbage collected.

Conclusion

In conclusion, the __del__ method in Python, while designed for object cleanup and resource management, suffers from unreliable execution timing. This unreliability stems from various factors such as the non-deterministic nature of garbage collection, the finalization queue, and potential concurrency issues in multi-threaded or asynchronous environments.

If you found it helpful, You can follow Rahul Beniwal for more articles in the future.

Other similar writings by me

Breaking the Mold: Concurrency Without Threads or AsyncioNavigating the Web Scraping Tool Landscape: A How-ToDecoding Python Magic : __getstate__ and __setstate__

Decoding Python Magic -> __del__ was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.

​ Level Up Coding – Medium

about Infinite Loop Digital

We support businesses by identifying requirements and helping clients integrate AI seamlessly into their operations.

Gartner
Gartner Digital Workplace Summit Generative Al

GenAI sessions:

  • 4 Use Cases for Generative AI and ChatGPT in the Digital Workplace
  • How the Power of Generative AI Will Transform Knowledge Management
  • The Perils and Promises of Microsoft 365 Copilot
  • How to Be the Generative AI Champion Your CIO and Organization Need
  • How to Shift Organizational Culture Today to Embrace Generative AI Tomorrow
  • Mitigate the Risks of Generative AI by Enhancing Your Information Governance
  • Cultivate Essential Skills for Collaborating With Artificial Intelligence
  • Ask the Expert: Microsoft 365 Copilot
  • Generative AI Across Digital Workplace Markets
10 – 11 June 2024

London, U.K.