On Thu, May 8, 2014 at 5:37 PM, Joseph Casale <jcas...@gmail.com> wrote: > For a trigger template something like: > > trg_template = """ > CREATE TRIGGER trg_foo_{0} > AFTER {0} ON foo > FOR EACH ROW > BEGIN > ... > END; > """ > > Why does the following not work to remove some redundant boiler plate code: > > for x in 'UPDATE', 'INSERT', 'DELETE': > > event.listen( > Foo.__table__, "after_create", > lambda *args, **kwargs: > DDL(trg_template.format(x)).execute(bind=engine) > ) > > Metadata create_all sees multiple definitions of the same trigger? >
You've been bitten by a Python gotcha! http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures Although your loop is setting up 3 distinct listener functions, they all contain a reference to the "x" variable which isn't evaluated until the function is called, long after your loop has finished. Each function will see the value of "x" at the time the function is *called*, which is probably the last value from the loop in this case. The easiest fix is probably something like this: def make_handler(operation, engine): trigger = trg_template.format(operation) return lambda *args, **kwargs: DDL(trigger).execute(bind=engine) for x in 'UPDATE', 'INSERT', 'DELETE': event.listen(Foo.__table__, "after_create", make_handler(x, engine)) Hope that helps, Simon -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.