Reputation: 691
When learning SQLAlchemy, the where()
clause in a query works like a magic since it expresses things quite naturally.
However, I couldn't understand why it works in this way.
Consider this query:
.where(MyTable.MyColumn == 1)
In theory, the parameter passed in Python is its value (reference could be considered as pointer value from my perspective), so MyTable.MyColumn == 1
is estimated (as a value) and then passed to the function. However, how this function behaves is like "estimating the value when executing the actual query" (i.e. just like a real SQL WHERE clause).
I understand a similar behavior in NumPy (e.g. np.argwhere(myarray > 0)
) is achieved by returning the boolean value of each element estimated in this condition and then performing actions on it. E.g. np.asarray([[0,1,2],[1,2,0]]) > 0
would result in array([[False,True,True],[True,True,False]], dtype=bool)
and np.argwhere()
simply operates on this value. I think SQLAlchemy may use a similar technique, but I still couldn't think out how they actually achieved it.
Could anyone give a brief explanation on why and how it works?
Upvotes: 4
Views: 466
Reputation: 5425
I bet that MyTable.MyColumn
overrides __eq__
. a == b
is essentially the same as a.__eq__(b)
.
So, MyTable.MyColumn
just has to override __eq__
to return a selector object rather than a bool.
Overloading Example: Try It Online!
Upvotes: 4