Hybrid list property: append not calling setter

407 views
Skip to first unread message

Avi Blackmore

unread,
Mar 17, 2018, 6:00:39 AM3/17/18
to sqlalchemy
I have a hybrid property with a custom setter defined for a one-to-many relationship on one of my classes, and for assignments using the = operator, it works fine.  I can assign a new list of objects to that property, and it calls the setter to handle the details.

But when I use the append() method on the list, the setter is not called.

How do I change this behavior?  I would like to be able to append, so I don't have to do silly things like obj.property = obj.property + [new].  That's not very Pythonic.

Thanks,

Avi Blackmore

Mike Bayer

unread,
Mar 17, 2018, 9:51:02 AM3/17/18
to sqlal...@googlegroups.com
we have to consider ordinary Python mechanics here. A hybrid
property is a Python descriptor, meaning it plugs in at the point at
which you set, access, and delete an attribute. A collection is
just any other value. But when we look into .append(), descriptors
have no access to that, if we look at:

myobject.attribute.append(foo)

that is really:

my_collection = myobject.attribute # <-- descriptor.__get__ is called
my_collection.append(foo) # <-- has nothing to do with the descriptor

so intercepting the append() has to do with what you're doing. if
you're returning the collection directly from a relationship attribute
then just use the append event:

http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.AttributeEvents.append

that event will be called for all new collection items even if a new
list is assigned. you also might want to use the bulk_replace event:
http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.AttributeEvents.bulk_replace
depending on what you're trying to do.



>
> Thanks,
>
> Avi Blackmore
>
> --
> SQLAlchemy -
> The Python SQL Toolkit and Object Relational Mapper
>
> http://www.sqlalchemy.org/
>
> To post example code, please provide an MCVE: Minimal, Complete, and
> Verifiable Example. See http://stackoverflow.com/help/mcve for a full
> description.
> ---
> 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+...@googlegroups.com.
> To post to this group, send email to sqlal...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.

Avi Blackmore

unread,
Mar 18, 2018, 4:58:53 AM3/18/18
to sqlalchemy
That is very helpful, thank you!  I will hook into the append event, I think.

Thanks very much.

Avi Blackmore
Reply all
Reply to author
Forward
0 new messages