[Python] How do I raise an exception when assigning to an attribute which is NOT mapped to an...

Discussão em 'Python' iniciado por Stack, Julho 12, 2025.

  1. Stack

    Stack Membro Participativo

    With SQLAlchemy, I'm finding that sometimes I mis-type a name of an attribute which is mapped to a column, which results in rather difficult to catch errors:

    class Thing(Base):
    foo = Column(String)


    thing = Thing()
    thing.bar = "Hello" # a typo, I actually meant thing.foo
    assert thing.bar == "Hello" # works here, as thing.bar is a transient attribute created by the assignment above
    session.add(thing)
    session.commit() # thing.bar is not saved in the database, obviously
    ...
    # much later
    thing = session.query(Thing)...one()
    assert thing.foo == "Hello" # fails
    assert thing.bar == "Hello" # fails, there's no even such attribute


    Is there a way to configure the mapped class so assigning to anything which is not mapped to an SQLAlchemy column would raise an exception?

    Continue reading...

Compartilhe esta Página