Iterating over a function call
Terry Reedy
tjreedy at udel.edu
Mon Feb 1 17:56:23 EST 2010
On 2/1/2010 11:50 AM, Gerald Britton wrote:
> Hi -- I have many sections of code like this:
>
> for value in value_iterator:
> value_function(value)
>
> I noticed that this does two things I don't like:
>
> 1. looks up "value_function" and "value" for each iteration, but
> "value_function" doesn't change.
What you mean by 'looks up'? And why are you bothered by normal Python
expression evaluation? Within a function, the 'look_up' is a fast
LOAD_FAST instruction.
> 2. side effect of (maybe) leaking the iterator variable "value" into
> the code following the loop (if the iterator is not empty).
So? it is sometime useful.
>
> I can take care of 2 by explicitly deleting the variable at the end:
>
> del value
>
> but I'd probably forget to do that sometimes.
So? If having 'value' bound breaks your subsequent code, I consider it
buggy.
I then realized that,
> in the 2.x series, I can accomplish the same thing with:
>
> map(value_function, value_iterator)
>
> and avoid both problems BUT map() returns a list which is never used.
> Not a big deal for small iterables, I guess, but it seems messy. Upon
> conversion to 3.x I have to explicitly list-ify it:
>
> list(map(value_function, value_iterator))
>
> which works but again the list returned is never used (extra work) and
> has to be gc'd I suppose (extra memory).
>
> It's easy to make a little function to take care of this (2.x):
>
> from itertools import imap
> def apply(function, iterable):
> for item in imap(function, iterable):
> pass
collections.deque(imap(function, iterable), maxlen=0)
will do nearly the same and may be faster.
> then later:
>
> apply(value_function, value_iterator)
>
> or something similar thing in 3.x, but that just adds an additional
> function def that I have to include whenever I want to do something
> like this.
>
> So.....I'm wondering if there is any interest in an apply() built-in
> function that would work like map() does in 2.x (calls the function
> with each value returned by the iterator) but return nothing. Maybe
> "apply" isn't the best name; it's just the first one that occurred to
> me.
>
> Or is this just silly and should I forget about it?
In my opinion, forget about it.
Terry Jan Reedy
More information about the Python-list
mailing list