Python generator in 30 seconds #shorts

preview_player
Показать описание
A Python generator function is a function that returns an object to the caller, which can be iterated over in a for-loop.

TAGS
#python #coding #programming #education #learnprogramming
Рекомендации по теме
Комментарии
Автор

Generators are very handy for database queries. Package up all the cursor creation, query execution and fetching of results in this:

def db_iter(conn, cmd, values = None, mapfn = lambda x : x) :
"executes cmd on a new cursor from connection conn and yields" \
" the results in turn."
for item in conn.cursor().execute(cmd, values) :
yield mapfn(item)
♯end for
♯end db_iter


and you conveniently collect and process the records like, for example, this:

for node in db_iter \
(
db,
"select %(fields)s from nodes where parent = %(itemid)d"
%
{"fields" : ", ".join(node_fields), "itemid" : itemid}
) \
:
node = dict(zip(node_fields, node))
get_terminals(node, node["id"], True)
nodes.append(node)
♯end for

lawrencedoliveiro
Автор

Not to be pedantic, but this sorta made me double take. The scripts as a whole are a good example because they print the same values, but the functions returning an array and iterator are not something you'd just want to change in existing code, in case something else calls that function and expects a list, with which they do operations that iterators can't handle. And you kinda mentioned the functions, not the whole scripts, so I was like confused for a second.

ttuurrttlle
Автор

I mean, the first approach wouldn't be so bad if python didn't had so much bloat behind the scenes, I'm talking about those things starting and ending with two underlines

night
Автор

I know this was a video about iterators, but the sum of all numbers from 0 to n (inclusive) is n*(n+1)/2.

rogerdunn