What is a "generator object" in django?

I use the Django voting package, and when I use the get_top () method in the shell, it returns something like a “generator object in 0x022f7AD0 , I have never seen anything like it before. How do I do this? You access it and what is it ?

my code is:

v=Vote.objects.get_top(myModel, limit=10, reversed=False) print v <generator object at 0x022f7AD0> 

NB: I thought get_top would just return a good myModel list, which I can do, like v.name , etc.

+4
source share
3 answers

If you need a list, just call list () on your generator object.

The python generator object is a bit of a lazy list. Elements are evaluated only after you iterate over them. (Thus, the calling list on it evaluates them all.)

For example, you can:

 >>> def f(x): ... print "yay!" ... return 2 * x >>> g = (f(i) for i in xrange(3)) # generator comprehension syntax >>> g <generator object <genexpr> at 0x37b6c0> >>> for j in g: print j ... yay! 0 yay! 2 yay! 4 

See how f is evaluated only as you iterate over it. You can find excellent material on this topic: http://www.dabeaz.com/generators/

+20
source

A generator is a kind of iterator. An iterator is a kind of iterable object and, like any other repeatable one,

You can iterate through each element with a for loop:

 for vote in Vote.objects.get_top(myModel, limit=10, reversed=False): print v.name, vote 

If you need to access elements by index, you can convert them to a list:

 top_votes = list(Vote.objects.get_top(myModel, limit=10, reversed=False)) print top_votes[0] 

However, you can iterate over only one iterator instance once (as opposed to a more general iterative object, such as a list):

 >>> top_votes_generator = Vote.objects.get_top(myModel, limit=3) >>> top_votes_generator <generator object at 0x022f7AD0> >>> list(top_votes_generator) [<Vote: a>, <Vote: b>, <Vote: c>] >>> list(top_votes_generator) [] 

For more information on creating custom generators, see http://docs.python.org/tutorial/classes.html#generators

+7
source

Hmmmm

I read this and this and now everything is calm,

In fact, I can convert generators to a list just by doing

 mylist=list(myGenerator) 
+1
source

All Articles