python - What are the advantages of using a generator function in the following case? -
the objective of assignment produce list elements indefinitely. did this:
servers = ['app1', 'app2', 'app3'] #servers = ['app1', 'app2', 'app3', 'app4', 'app5', 'app6'] length = len(servers) def get_server(): current_server = servers.pop(0) servers.append(current_server) return current_server if __name__ == '__main__': in range(9): print get_server()
the solution has this:
servers = ['app1', 'app2', 'app3'] #servers = ['app1', 'app2', 'app3', 'app4', 'app5', 'app6'] def get_server(): def f(): while true: = servers.pop(0) servers.append(i) yield return next(f()) if __name__ == '__main__': in range(9): print get_server()
the output although same in both cases:
codewingx@codelair:~/repo/python$ python load_balancer.py app1 app2 app3 app1 app2 app3 app1 app2 app3
so how generator function beneficial?
use itertools.cycle()
the generator not add useful here. try avoid pop(0)
triggers rebuild of whole server list each time.
i recommend itertools.cycle():
from __future__ import print_function itertools import cycle servers = ['app1', 'app2', 'app3'] servers = cycle(servers) in range(9): print(next(servers))
output:
app1 app2 app3 app1 app2 app3 app1 app2 app3
our wrapped in function match usage:
def make_get_server(): servers = cycle(servers) def get_server(): return next(servers) return get_server get_server = make_get_server() in range(9): print(get_server())
output:
app1 app2 app3 app1 app2 app3 app1 app2 app3
write own generator function
to make point generator, variation takes advantage of ability store stet might more useful:
def gen(): index = 0 end = len(servers) while true: yield servers[index] index += 1 if index >= end: index = 0
while illustrates nicely have state working index
, same can achieved more with:
def gen(): while true: server in servers: yield server g = gen() def get_server(): return next(g)
this avoids modifying list of servers
. result same:
for in range(9): print(get_server())
output:
app1 app2 app3 app1 app2 app3 app1 app2 app3
how generator works
a simple generator function:
>>> def gen(): ... print('start') ... yield 1 ... print('after 1') ... yield 2 ... print('after 2') ...
make instance:
>>> g = gen()
use next
next value returned yield
:
>>> next(g) start 1
keep going:
>>> next(g) after 1 2
now exhausted:
>>> next(g) after 2 stopiteration next(g)
you may think of cursor moves along in generator function. every time call next()
moves next yield
. putting yield
in while true
loop makes infinite generator. long don't call close()
on it, gives new value yield
. also, have state inside generator. means can things incrementing counters between calls next()
.
Comments
Post a Comment