avoid for loop calling Generator function

Ian Kelly ian.g.kelly at gmail.com
Mon Feb 22 11:11:11 EST 2016


On Mon, Feb 22, 2016 at 8:38 AM, Arshpreet Singh <arsh840 at gmail.com> wrote:
> On Monday, 22 February 2016 19:05:24 UTC+5:30, Peter Otten  wrote:
>> or the slightly less convoluted
>>
>> sys.stdout.writelines(map("{}\n".format, read_pdf("book.pdf")))
>
> Actually I am using this function in Android App which is being built
using Kivy, Where I am returning whole text into a file, So what you think
will be more efficient way?

Profile them and find out, but I don't think you'll find the difference is
great enough to be overly concerned with. Pick the way that is more
readable and doesn't introduce any gross inefficiencies (such as
concatenating strings in a loop).

> But when I am calling pdf_read() from nother function to avoid for loop
why it is not working?
> say:
>
> def hello()
>     yield from read_pdf('book.pdf')

This uses yield from, which makes it a generator function.

>
> print(hello()) # still returns memory location instead of text. If I am
not wrong yield from can be used to avoid for loop?

hello is a generator function, so calling it just creates a generator
object. Printing it then prints out the repr of that generator object,
which is just something like <generator object hello at 0x7f6e82b124c0>.

Notably, you haven't actually *executed* the generator object, which would
require iterating over it, e.g.:

for i in hello():
    print(i)

So you haven't actually avoided creating a for loop; you've just added a
redundant layer between the for loop and the thing it's actually iterating
over.


More information about the Python-list mailing list