I am looking at some Web2py code.
The variable tokens
is some kind of a list of strings. To be more precise, it is defined as tokens = form.vars.name.split()
where form.vars.name
is a string.
My question deals with the following instruction :
query = reduce(lambda a,b:a&b,[User.first_name.contains(k)|User.last_name.contains(k) for k in tokens])
Here are my questions :
I know
lambda a,b:a&b
defines a function ofa
andb
. What isa&b
?Is the
contains
method ofUser.first_name
specific to Web2py ? Or does it exist in standard Python ?What 开发者_如何学Cis this
|
operator inUser.first_name.contains(k)|User.last_name.contains(k)
?What does the
reduce
function do ?
- In Web2Py
&
and|
are not bitwise and/or here, but are used to build a special object that represents a database query! They correspond toAND
andOR
in SQL statements - contains is part of Web2Pys DAL
- See 1.
- reduce is fold, a very fundamental higher order function that essentially reduces a list to a result, using the function given.
- Bitwise and.
- I believe contains, in that context is more-or-less a mapping to
__contains__
, but it does appear in Py3k docs. - Bitwise or.
- reduce iterates through an iterable object (param 2) and calls the passed function (param 1) on all of the elements. It returns the aggregate value.
&
is the bitwise and operator. The person writing the code almost certainly meantand
, although for boolean values the result is the same..contains()
is a method provided by web2py.a.contains(b)
is more pythonically written asb in a
.|
is the bitwise OR operator. Again, they probably meantor
.reduce
applies the function given as the first argument to the iterable in the second argument, from left-to-right, first with the first 2 elements, then with the result of that calculation and the third element, etc.
精彩评论