"AssertionError: Collection was loaded during event handling." exception raised after loading a collection in a validator method

Issue #1916 resolved
Former user created an issue

If a validator is used on a model and that validator loads a relation from that model, an AssertionError can occur as SqlAlchemy assumes no collections have been loaded after the validator has been called.

The following test script demonstrates the issue (as of sqlalchemy 0.5.8). The resulting stacktrace is this:

Traceback (most recent call last):
  File "test.py", line 37, in <module>
    model2.parent = model1
  File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/attributes.py", line 150, in __set__
    self.impl.set(instance_state(instance), instance_dict(instance), value, None)
  File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/attributes.py", line 590, in set
    value = self.fire_replace_event(state, dict_, value, old, initiator)
  File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/attributes.py", line 610, in fire_replace_event
    value = ext.set(state, value, previous, initiator or self)
  File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/attributes.py", line 848, in set
    new_state.get_impl(self.key).append(new_state, new_dict, state.obj(), initiator, passive=PASSIVE_NO_CALLABLES)
  File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/attributes.py", line 710, in append
    assert self.key not in dict_, "Collection was loaded during event handling."
AssertionError: Collection was loaded during event handling.

If this is expected behavior, then perhaps the documentation should be more clear as to the limitations of these validators.

Comments (5)

  1. Mike Bayer repo owner

    Replying to guest:

    If this is expected behavior, then perhaps the documentation should be more clear as to the limitations of these validators.

    you got it, 2ab0687ece8e027f31cc0861021ef040b90167a4 .

    Note that if you see an explicit assertion in the source code catching exactly what you're doing, it's safe to assume that is the behavior as designed.

  2. Mike Bayer repo owner

    Also see #1526 for the original rationale. If you'd like to assist in removing this assertion, you'd have to figure out how to prevent the corruption which occurs in that test in a more granular way.

  3. Mike Bayer repo owner

    i.e. try taking out the assertion, then add this to your script:

    assert len(model1.children) == 1
    

    fails. isn't an exception better than silent failure ?

  4. Log in to comment