Python — try … finally versus with

DevTechie
DevTechie
Published in
6 min readSep 1, 2024

--

Python — try … finally versus with

In Python, both try . . . finally and with statement can be used ‌for resource management. Let’s explore the differences between them in this article.

Background

One typical programming difficulty is how to manage external resources like files, locks, and network connections. Sometimes a program will acquire those resources indefinitely, even if the program no longer requires them. This is known as a memory leak because it reduces available memory every time you create and open a new instance of a particular resource without first closing an existing one.

Managing resources effectively is often a difficult task. It involves both a setup and a teardown step (cleanup step). The later phase necessitates some cleanup operations, such as closing a file, releasing a lock, or terminating a network connection. If you forget to conduct these cleanup actions, your application will keep the resource alive even if not actively using it. This could jeopardize critical system resources such as memory and network bandwidth.

A common issue that can happen when developers interact with databases is when a program repeatedly creates new connections without retiring or reusing them. In those circumstances, the database backend may stop accepting new connections. To restore database functionality, an administrator may need to log in and…

--

--