1

For brevity I am just giving an example table and no other configuration.

class Widget(Base):
    id = Column(Integer, primary_key=True)


#Setup/config logic goes here.
# assume session object exists.

thing = Widget()
thing.foo = "bar"
#ideally throw atleast a warning that `foo` doesn't exist
session.add(thing)

Sqlalchemy will ignore foo being assigned to the record instance, I can understand why, but is there someway to catch these assignments?

Would I need to add my own __init__ with some sort of getattr to implement a freeze/lock logic to the class or does sqlalchemy have something like this provided?

I caught a typo in my code where I meant to assign to a net_amount field and instead assigned to the non-existent met_amount and would like to somehow catch these bugs before they get to far out of control.

David
  • 17,673
  • 10
  • 68
  • 97
  • 1
    I would definitely provide custom logic in `__getattr__` function. There is also a possibility to define `__slots__` class variable which also can take care of such things, but I think SQLAlchemy internally make use of that so I would not risk. – bc291 Mar 05 '19 at 23:35
  • @needtobe What little inspection I've done, it feels like getattr is the safer choice but even that might get complicated because of the extra attributes declarative adds to domain tables. – David Mar 06 '19 at 03:51
  • You probably don't want to override `__getattr__`: https://stackoverflow.com/questions/32334733/sqlalchemy-doesnt-seem-to-like-getattr. – Ilja Everilä Mar 06 '19 at 08:15
  • You could possibly wrap `__getattr__` in a decorator that logs the fact that it's been called or, inspects the instance and logs whether or not your attribute name is a column name. I've never done this though, so testing required. – snakecharmerb Mar 06 '19 at 08:26

0 Answers0