I just recently had a chance to take a look at web2py framework and although I have some prior experience with Django and more so with plain Python, I couldn’t make sense out of the Query system that web2py employs.
Let’s take this example from web2py book
db = DAL('sqlite://storage.db')
myquery = (db.mytable.myfield > 'A')
myset = db(myquery)
rows = myset.select()
for row in rows:
print row.myfield
In a SO comment web2py author says that (db.mytable.myfield > 'A') does not evaluate to True/False directly and it’s actually evaluated for each row at the time of selection. I understand this is what allows these expressions to be used as query objects and even be combined.
I’ve tried to find an answer to this online but couldn’t, so here is my question: How is those query expressions are not evaluating to True/False right away? Why is value of myquery is not, say, True? What Python feature that I’m probably missing allows this to work?
The other answers have it, but just to provide a little more web2py-specific detail:
db.mytable.myfieldis an instance of the web2py DALFieldclass, which inherits from the DALExpressionclass. TheExpressionclass itself overloads a number of Python operators, such as==,<,>, etc. These overloaded operators, when applied toExpression(and thereforeField) objects return an instance of the DALQueryclass rather than a standard Python boolean object. Here is the source code for the>(__gt__) operator.See here for more on operator overloading in Python.