Comparing SQLAlchemy Object Instances for Equality of Attributes

I’ll drill down into what’s happening behind the Base class, to show that the __eq__ and __ne__ overrides are fine. When you instantiate your Base class by calling declarative_base(), it’s using a metaclass behind the scenes to set it up (It might be worth reading this explanation this metaclass explanation to better understand why it is involved). It does some configurable setup, like adding a custom constructor to your Base class and setting how it will map from the object to a table.

declarative_base()is then going to return a new Base class instance of a DeclarativeMeta metaclass. The whole reason metaclasses are involved here are so that at the time when you create a class that extends your Base, it will map it to a table. If you trace down this path a little way, you will see how it maps the Columns you declare on your object to a table.

self.cls.__mapper__ = mp_ = mapper_cls(
        self.cls, # cls is your model
        self.local_table,
        **self.mapper_args # the columns you have defined
    )

Although the actual Mapper which is doing this looks like it gets very complicated and low level, at this stage it’s operating with primary keys and columns rather than actual object instances. This doesn’t confirm that it’s never used, however, so I looked through the usages of == and != on the source and didn’t see any causes for concern.

As for your second question I can only really offer my own opinion – I’ve googled around this subject many times in the past and haven’t found much in the way of ‘gold standard’ SQL Alchemy usage. I’ve used SQL Alchemy for a couple of projects so far and it feels like your use of the objects can extend about as far as you can still sensibly abstract away the session life-cycle. To me it seems like enough of the Alchemy “magic” is abstracted away from the models themselves that when sessions are handled well, they are sufficiently far removed from the data layer that it doesn’t feel like business logic in the classes would get in the way.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)