[Python-ideas] Anonymous blocks (again):
Steven D'Aprano
steve at pearwood.info
Mon May 13 11:11:21 CEST 2013
On Mon, May 13, 2013 at 03:17:15PM +1000, Nick Coghlan wrote:
> 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.
I'm obviously still missing something, because I'm aware of Ruby's
blocks, but I don't quite see how they apply to Juancarlo's *specific*
use-case, as described above.
Unless Juancarlo's use-case is more general than I understood, it seems
to me that we don't need blocks, anonymous or otherwise, to "invoke a
block of code repeatedly, within a context", in a Pythonic way.
Perhaps a concrete (even if toy or made-up) example might help me
understand. The only thing I can think of is, if I had a bunch of
similar loops inside the same context, where only the body of the loop
was different, I might want to factor it out something like this:
the_block = {define a block of code, somehow}
def do_stuff(block):
with context:
while condition:
{execute the block of code}
do_stuff(the_block)
do_stuff(another_block)
but I think that requires new syntax, and Juancarlo specifically says he
doesn't want new syntax.
--
Steven
More information about the Python-ideas
mailing list