Last value of yield statement

Paul Hankin paul.hankin at gmail.com
Wed Oct 10 08:04:52 EDT 2007


On Oct 10, 11:19 am, Shriphani <shripha... at gmail.com> wrote:
> Hello all,
>
> Let us say I have a function like this:
>
> def efficientFiller(file):
>         worthless_list = []
>         pot_file = open(file,'r')
>         pot_file_text = pot_file.readlines()
>         for line in pot_file_text:
>                 if line.find("msgid") != -1:
>                         message_id = shlex.split(line)[1]
>                         if message_id in dictionary:
>                                 number = pot_file_text.index(line)
>                                 corresponding_crap =
> dictionary.get(message_id)
>                                 final_string = 'msgstr' + " " + '"' +
> corresponding_crap + '"' + '\n'
>                                 pot_file_text[number+1] = final_string
>                                 yield pot_file_text
>
> efficient_filler =  efficientFiller("libexo-0.3.pot")
> new_list = list(efficient_filler)
> print new_list
>
> I want to plainly get the last value the yield statement generates.
> How can I go about doing this please?

If you want only one value, you should be using return rather than
yield. What do you think your code does - and what is it supposed to
do? If it's not doing what it's supposed to be doing, it's better to
understand why not rather than try to patch up the output.

I'm going to guess that you want to take the lines of a file, and
after every line of the form 'msgid K' insert a line 'msgstr "..."'
when K is in some dictionary you've got. I'll assume you want the new
lines as a generator rather than as a list.

Then, something like (untested)

def lookup_msgids(filename):
    """Yield lines from the given file, with 'msgstr' lines added
       after 'msgid' lines when the id is in the id dictionary."""
    for line in open(filename, 'r'):
        yield line
        if line.startswith('msgid'):
            msgid = shlex.split(line)[1]
            if msgid in dictionary:
                yield 'msgstr "%s"\n' % dictionary[msgid]


libexo_pot = list(lookup_msgids('libexo-0.3.pot'))
print libexo_pot

--
Paul Hankin




More information about the Python-list mailing list