[Python-ideas] Anonymous blocks (again):

Nick Coghlan ncoghlan at gmail.com
Mon May 13 07:17:15 CEST 2013


On Mon, May 13, 2013 at 2:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 13/05/13 13:58, Juancarlo Añez wrote:
>
>> I don't want new syntax (I think I don't).
>>
>> What I want is to be able to invoke a block of code repeatedly, within a
>> context, and in a pythonic way.
>
>
> Surely that would be:
>
> with context():
>     while condition: # or a for loop
>         block of code goes here
>
>
> If you want something different to this, then I think you do want new
> syntax. Otherwise, what do you gain beyond what can already be done now?
>
> Or am I missing something?

Ruby uses anonymous callbacks for things where Python instead uses
dedicated syntax:

Python -> Ruby

decorated function definitions -> callbacks
for loops + iterator protocol -> callbacks
with statements + context management protocol -> callbacks
callbacks -> callbacks (but with much nicer syntax)

Blocks are a *really* nice way of doing callbacks, so nice that Ruby
just doesn't have some of the concepts Python does - it uses callbacks
instead.

While I have no real interest in Ruby's use of embedded callbacks
inside expressions (or various other pieces of control flow magic that
Ruby blocks support), I *do* think their ability to easily supply a
full nested callback to a single statement is valuable, and gets to
the heart of people's interest in multi-line lambdas in Python. PEP
403 is mostly about adapting that feature to an ecosystem which
doesn't have the "the callback is the last positional parameter"
convention that the block syntax established for Ruby. Using a forward
reference to a class instead lets you have multiple forward references
through attribute access.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list