Issue #2650 resolved

ad-hoc subclasses of event-bound classes don't get garbage collected

Mike Bayer
repo owner created an issue

but does in 0.8

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
import weakref
import gc

the_weak_ref = None
engine_is_removed = False

def engine_removed(ref):
    global engine_is_removed
    engine_is_removed = True
    print "Engine was GCed!"

def create_sn(url):
    global the_weak_ref
    engine = create_engine(url)
    the_weak_ref = weakref.ref(engine, engine_removed)
    # this works
    #return Session(bind=engine, expire_on_commit=False)
    return sessionmaker(bind=engine) #(expire_on_commit=False)

sn = create_sn("sqlite://")
sn = sn()
sn.execute("select 1")

print "about to delete sn..."
del sn

print "about to gc.collect()..."

assert engine_is_removed

Comments (5)

  1. Mike Bayer reporter

    because 0.7 creates a Session subclass, once an event fires off for that subclass it gets placed into the dispatch, which makes it permanent.

  2. Mike Bayer reporter

    Ah and 0.8 also has this permanent Session subclass, but the Engine isn't stuck in it. So we have a potential memory leak here, if someone is creating and removing lots of sessionmakers.

  3. Log in to comment