A little abstraction, less repetition

Users of SQLAlchemy frequently write code like this
session.query(Person).filter(Person.id == some_id, Person.disabled.isnot(True)).first() session.query(Cat).filter(Cat.id == some_id, Cat.disabled.isnot(True)).first() session.query(Dog).filter(Dog.id == some_id, Dog.disabled.isnot(True)).first()
When we work on a application with several entities, the way we get this data from a database is usually very similar and repetitive. Also, it’s common to use some sort of flag that exists in all entities for filtering. On the above sample, the disabled property is used for that purpose: “we want the id X but only if it’s not disabled”
Since this is the default for all the application, why not abstract it a little?
def get_one(class_, item_id): return ( session.query(class_).filter(class_.id == item_id, class_.disabled.isnot(True)).first() )
Now we can do something like this:
person = get_one(Person, 1) cat = get_one(Cat, 1) dog = get_one(Dog, 1)
Very simple as you can see but also very rare to be found on the code out there.
I’m certain that we can find some little repetitive code that we can abstract like this.
See ya!