http://qs321.pair.com?node_id=1030261


in reply to Re^2: RFC: Simulating Ruby's "yield" and "blocks" in Perl
in thread RFC: Simulating Ruby's "yield" and "blocks" in Perl

FWIW, the equivalent in idiomatic Python3 is:
def test() print("You are in the method") yield 1 print("You are again back to the method") yield 2 for a in test(): print("You are in the block #{}".format(a))
As for anonymous multiline blocks, a while back a monstrosity was released...

Replies are listed 'Best First'.
Re^4: RFC: Simulating Ruby's "yield" and "blocks" in Perl (Python)
by LanX (Saint) on Apr 24, 2013 at 04:19 UTC
    > FWIW, the equivalent in idiomatic Python3 is:

    Thanks, interesting idea to turn it inside out!¹ =)

    But why Python3, AFAIK generators were already introduced in 2.

    > while back a monstrosity was released...

    Thanks, even more fun! =)

    Especially the last line (after "bugs and limitations")

    Oh, and almost forgot: We are sorry, Guido. So sorry.

    Grin! xD

    Cheers Rolf

    ( addicted to the Perl Programming Language)

    update

    ¹) while its a bit cumbersome that you need to iterate over the yields... ... why not using a decorator to abstract the loop away?

    update

    this worked for me in Py 2.5.2

    >>> def test(): ... print("You are in the method") ... yield 1 ... print("You are again back to the method") ... yield 2 ... >>> for a in test(): ... print("You are in the block "+str(a)) ... You are in the method You are in the block 1 You are again back to the method You are in the block 2
      v3 is current, though str.format() was added in late v2 releases for compatibility (printf style interpolation is to be deprecated some time but I'll use it below as an example...). Here's the decorated version as suggested:
        > I don't really see a win with this style, though, over giving test a parameter, and just using standard function calls (I had a little play with coroutines on the way but that's really overkill for this).

        Well I expected decorators to be more flexible, i.e. to redefine test() by putting a wrapper around it and not to built a new decorator @test (!?!)

        But I'm not too proficient with Python, and I'm misunderstanding the code.

        (well, there must be a reason why I prefer Perl's syntactic flexibility. ;-)

        I suppose def _(a) is a way to workaround the limitations of lamda?

        Is the name _ special (magic) or is it just a convention?

        Cheers Rolf

        ( addicted to the Perl Programming Language)