Operator overloading or alternatives to expression templates

Jack Stouffer via Digitalmars-d digitalmars-d at puremagic.com
Sun Sep 13 06:15:26 PDT 2015


On Saturday, 12 September 2015 at 22:38:53 UTC, Bahman Movaqar 
wrote:
> Django's approach is, IMO,  the cleverest and least magical one 
> while keeping it expressive and efficient:
>
>     Person.objects.filter(age__gt=21, name__eq='peter')

As the main examples in this thread are for ORMs, I think the 
best case for more powerful operator overloading is the very 
popular Python library SQLAlchmey. SQLAlchmey is the reason that 
any project of mine that requires a database is going to be in 
Python.

Here is a real code sample from one of my projects from my day 
job:

shipped = session.query(
         func.sum(
             InvoiceHistoryDetail.QuantityShipped * 
InvoiceHistoryDetail.UnitPrice
         ).label("sum")
).join(
         InvoiceHistoryHeader,
         InvoiceHistoryHeader.InvoiceNo == 
InvoiceHistoryDetail.InvoiceNo
).join(
         Customer,
         and_(
             InvoiceHistoryHeader.ARDivisionNo == 
Customer.ARDivisionNo,
             InvoiceHistoryHeader.CustomerNo == Customer.CustomerNo
         )
).filter(
         InvoiceHistoryHeader.ShipDate >= 
fiscal_month.PeriodStartingDate,
         InvoiceHistoryHeader.ShipDate == datetime.date.today() - 
datetime.timedelta(days=1),
         InvoiceHistoryHeader.SalesOrderNo != None,
         Customer.UDF_PARTICIPATION.in_(participation)
).one()

Note how complex operator overloading is used to make very 
readable JOIN and WHERE clauses. One other cool thing to note is 
the func function, which is a generator function that allows 
expressing any SQL function in Python by translating the name 
after the dot to the function name is the final SQL. So 
func.whatever(model.field) would become WHATEVER(`model.field`) 
in the SQL.

I know that this effect is much harder to create in a explicitly 
and strongly typed language, but I just wanted to show a real 
world example of how these could be used to great effect.


More information about the Digitalmars-d mailing list