I think you're hitting an edge case here that's the result of trying to use objects across sessions where you're just allowing sessions to fall out of scope. I'm not sure the behavior as is is how it should be. The source to _attach() implies that "implicit detachment" was how this worked at some point, or intended to work but there's no tests - I was under the impression that the object is in fact implicitly detached, but that doesn't occur here without a small change. http://www.sqlalchemy.org/trac/ticket/2281 sums up the behavior.
The questions I'd start with, and keep in mind this is towards establishing a use case that would drive the desired behavior, is what is preventing you from keeping a Session in place, or calling close() on it when completed, or using new objects for a new Session instead of recycling those which are hanging around from some previous operation ? That said I'm leaning towards that patch, but probably only in 0.7 as it is a slight behavioral change.
Hi Mike,It is an edge case for sure. I'm using SA with eventlet so the session is going out of scope in a green thread. Eventlet does some monkeying (literally) around with threadlocals so I get a different session for each one. However in this case the parent instance to which I'm adding obj was fetched in a one greenthread and the child is added in another after a timer has fired off (the child is a record of the timer running). It's definitely fair to say that I'm not using SA in an optimal way, however I'd still be inclined to say that the patch could be worthwhile here.
Is there any particular reason that you added the check where you did in the patch as opposed to the except KeyError clause in _state_session?