To find all instances of the Database class in the current IPython session and check the connections, you can use the following function. It uses the gc.get_objects() function to iterate over all live objects, checks if they are instances of the Database class, and then tests the connections.
import gc
import pyodbc
class Database: # Example class, replace it with your actual Database class
def __init__(self, connection):
self.connection = connection
def get_open_connections():
open_connections = []
for obj in gc.get_objects():
if isinstance(obj, Database):
connection = obj.connection
try:
# Execute cursor() to check if the connection is open
connection.cursor()
open_connections.append(connection)
except pyodbc.Error:
# If an error occurs, the connection is likely closed
continue
return open_connections
# Example usage:
open_connections_list = get_open_connections()
Keep in mind that using gc.get_objects() may not be the most efficient or recommended way to keep track of your objects, especially in a real-world scenario. It would be better to manage your OrderDirectory instances in a more explicit way, such as by keeping them in a list or dictionary.
To find all instances of the
Database
class in the current IPython session and check the connections, you can use the following function. It uses thegc.get_objects()
function to iterate over all live objects, checks if they are instances of theDatabase
class, and then tests the connections.Keep in mind that using
gc.get_objects()
may not be the most efficient or recommended way to keep track of your objects, especially in a real-world scenario. It would be better to manage yourOrderDirectory
instances in a more explicit way, such as by keeping them in a list or dictionary.