Note that this isn't a complete solution: bad Python code can still reference a freed pointer (e.g., by using a cursor after closing the session that was used to allocate the cursor). Solving that problem completely would involve tracking ownership in Python.