Reputation:
I am sorry for not providing example code. But I wasn't able to reproduce this outside my own code.
I have dialog object (wx.Dialog
) that has a list
of sqlalchemy-mapped objects.
The dialog is closed and destroyed correct. I checked that with debug code, id()
and __del__()
.
But when I open the dialog again (pushing the related button in the main window) the same instances of the sqlalchemy-mapped objects are still in the list
. The dialog object is new in RAM but its list witht the data objects is the same from the first dialog instance. I am confused.
Currently I call self._datalist.clear()
in the __del__()
of the dialog. Then it works.
But I am not sure why this happens and if my solution is elegant?
Upvotes: 0
Views: 2121
Reputation: 156238
In python, you don't "delete" things to make them go away, and you almost never want to use __del__()
for much of anything; python is a garbage collected language, you just "forget" objects and they will be freed eventually.
The problem you're most likely having is that while your own code forgets the objects themselves, the SQLAlchemy session()
object you retrieved them from has not forgotten them. In fact, this is the precise thing session
is for, when two rows are retrieved from the database with the same primary key values, they become the same object in python.
You most likely want to dispose of the whole session between logical units of work (for example, a user interaction ending in "Save"). for that, you can use session.close()
. After that, you can continue using the session; a new transaction will start when needed, or obtain a new session in the same way you got the first one.
If you really need to manage object lifetime per object, you can use session.expunge()
, but only do that if you have a good understanding of what the session is really doing for you. A good place to start is the State Management
chapter in the docs:
Upvotes: 1