Always close resources explicitly and ensure proper cleanup even if an error occurs.
Improper resource shutdown or release happens when a program allocates a resource, such as a file, socket, or database connection, and fails to release it when finished. Unlike normal objects (like numbers or strings), these resources are tied to the operating system and are not freed automatically by garbage collection. If left open, they can pile up and cause memory leaks, file handle exhaustion, or stalled network connections.
In Python, use the with
statement to ensure handles are cleaned up automatically; note that with
manages resource cleanup, not memory deallocation. Special care is required for long-running scripts, multiprocessing, or multithreading, where lingering handles can accumulate over time and exhaust system resources.
In this noncompliant01.py
code example, two elements are added to the list. Although the list continues to hold these two elements, they are never properly released, leading to retained memory that is never reclaimed. This can cause resource exhaustion or leaks.
"""Non-Compliant Code Example"""
my_list = []
def append_resource(name):
print(f"Allocating resource {name}")
resource = {"name": name, "active": True} # Simulated resource
my_list.append(resource)
append_resource("A")
append_resource("B")
# Forgot to release resources
#####################
# attempting to exploit above code example
#####################
for resource in my_list:
print(resource["name"], "active?", resource["active"])
if not any(resource["active"] for resource in my_list):
print("All resources released.")
After adding two elements, to the list, the list in this compliant01.py
code example now contains zero elements because they have been cleared and properly released.
"""Compliant Code Example"""
my_list = []
def append_resource(name):
print(f"Allocating resource {name}")
resource = {"name": name, "active": True} # Simulated resource
my_list.append(resource)
append_resource("A")
append_resource("B")
# Properly release resources
for resource in my_list:
resource["active"] = False
my_list.clear()
#####################
# attempting to exploit above code example
#####################
for resource in my_list:
print(resource["name"], "active?", resource["active"])
if not any(resource["active"] for resource in my_list):
print("All resources released.")
[Python Docs] | https://docs.python.org/3/tutorial/datastructures.html |