this seems nice.

It just seems that the obvious way to do it would be:

def tap(iter_, func):

   for item in iter_:
       func(item)
       yield item



I think it can be nice, but more as cookbook material than an actual itertools function.



On Sun, 25 Oct 2020 at 14:38, <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:
On 2020-10-25 at 16:34:14 +0000,
George Harding <george.winton.harding@gmail.com> wrote:

> some_iter = map(lambda x: x if print(x) else x, some_iter)
>
> The tuple has a ~50% overhead, the case statement ~15%, compared to the
> generator.

    def print_first(x):
        print(x)
        return x
    new_iter = map(print_first, some_iter)

No extranous tuple, no extranous case stament.  Newlines are cheap these
days.  The call to print, however, is possibly unbounded in time and
space.

If you really want to go overboard, put something like the following
peeker function into your personal toolbox (untested):

    def peeker(function):
        def peeker(x):
            function(x)
            return x
        return peeker

And use it like this:

    new_iter = map(peeker(print), some_iter)
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/RG2ZQD5NNU2BKVTC2AZGSQNVZA2CV2UJ/
Code of Conduct: http://python.org/psf/codeofconduct/