Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "generator object" in django?

Am using Django voting package and when i use the method get_top() in the shell, it returns something like "generator object at 0x022f7AD0, i've never seen anything like this before, how do you access it and what is it?

my code:

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

NB: I thought get_top will just return a nice list of myModel, which i can do something like v.name etc

like image 479
gath Avatar asked Apr 22 '09 07:04

gath


3 Answers

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

A generator object in python is something like a lazy list. The elements are only evaluated as soon as you iterate over them. (Thus calling list on it evaluates all of them.)

For example you can do:

>>> 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 the topic here: http://www.dabeaz.com/generators/

like image 183
bayer Avatar answered Sep 20 '22 11:09

bayer


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

You can iterate over every item using a for loop:

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

If you need to access items by index, you can convert it to a list:

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

However, you can only iterate over a particular instance of an iterator once (unlike a more general iterable object, like 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 on creating your own generators, see http://docs.python.org/tutorial/classes.html#generators

like image 20
Miles Avatar answered Sep 20 '22 11:09

Miles


Hmmmm

I've read this and this and things are quiet clear now;

Actually i can convert generators to list by just doing

mylist=list(myGenerator)
like image 37
gath Avatar answered Sep 17 '22 11:09

gath