Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #103346

Re: avoid for loop calling Generator function

From Ian Kelly <ian.g.kelly@gmail.com>
Newsgroups comp.lang.python
Subject Re: avoid for loop calling Generator function
Date 2016-02-22 09:11 -0700
Message-ID <mailman.43.1456157520.20994.python-list@python.org> (permalink)
References <e5e4a934-4eeb-46ed-892f-cda9e903c1cd@googlegroups.com> <mailman.40.1456148110.20994.python-list@python.org> <0c289f93-ce64-4eff-93f3-c70d7ff50817@googlegroups.com>

Show all headers | View raw


On Mon, Feb 22, 2016 at 8:38 AM, Arshpreet Singh <arsh840@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.

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

avoid for loop calling Generator function Arshpreet Singh <arsh840@gmail.com> - 2016-02-22 03:15 -0800
  Re: avoid for loop calling Generator function Peter Otten <__peter__@web.de> - 2016-02-22 14:34 +0100
    Re: avoid for loop calling Generator function Arshpreet Singh <arsh840@gmail.com> - 2016-02-22 07:38 -0800
      Re: avoid for loop calling Generator function Chris Angelico <rosuav@gmail.com> - 2016-02-23 02:46 +1100
      Re: avoid for loop calling Generator function Ian Kelly <ian.g.kelly@gmail.com> - 2016-02-22 09:11 -0700

csiph-web