[Tutor] Misc question about scoping

spir denis.spir at gmail.com
Fri Jun 4 23:08:42 CEST 2010


On Fri, 4 Jun 2010 12:26:20 -0400
Tino Dai <oberoc at gmail.com> wrote:

> Also could you give me some instances
> where a generator
> would be used in a real situation? I have already read the stuff on
> doc.python.org about
> generators.

Sure, generally speaking in the programming world, documentation misses the first and principle step: *purpose* :-) Why is that stuff intended for?

My point of view is as follows (I don't mean it's _the_ answer):
Generators are useful when not all potential values need be generated (or possibly not all). Meaning you perform some task until a condition is met, so you don't need all possible map values. A mapping or list comprehension instead always creates them all.

A particuliar case where a generator is necessary is the one of an "open", unlimited,  series, defined by eg a formula, such as cubes. Such a potentially infinite series is only broken by a loop break:

def cubes(first):
	n = first
	while True:
		yield n ** 3
		n += 1

for cube in cubes(1):
	if cube > 999:
		break
	else:
		print(cube),

Denis
________________________________

vit esse estrany ☣

spir.wikidot.com


More information about the Tutor mailing list