[Tutor] Generator expressions...

Hugo Arts hugo.yoshi at gmail.com
Sun Feb 27 22:45:54 CET 2011


On Sun, Feb 27, 2011 at 10:34 PM, Modulok <modulok at gmail.com> wrote:
>
> import hashlib
>
> fd = open('/dev/urandom', 'rb')
> gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096))
>
> try:
>    for i in gen:
>        print i     #<-- This loop should never end... but does. Why?
>
> except KeyboardInterrupt:
>    gen.close()
>    fd.close()
>    print "\nBye!"
>

Check out the generator expression. What are you iterating over? How
long is the string returned by the read? Obviously, it isn't of
infinite length. Then why are you expecting the generator expression
to run forever? Remember that a generator expression isn't like a
function. You can't call it multiple times. You iterate over it once,
then it's done, and you'll have to create a new one.

HTH,
Hugo


More information about the Tutor mailing list