Re: Ruby blocks in Python, a suggestion

From: Lonnie Princehouse (fnord_at_u.washington.edu)
Date: 04/13/04


Date: 13 Apr 2004 14:05:25 -0700

Yes!

hungjunglu@yahoo.com (Hung Jung Lu) wrote:
> def my_codeblock:
> assert(y == x*2)
>
> for (x,y) in [(1,2), (2,4), (3,6)]:
> exec my_codeblock

This is by far the prettiest syntax for blocks presented thus far =)
A function really is just a special case of a code block that (a)
operates within its own scope and (b) defines a mapping between that
scope and the calling scope. This syntax preserves that relationship,
while also avoiding adding new keywords like "defblock" to the
language. I would go so far as to say the code block should be
callable just like a function that takes no arguments-

def my_codeblock:
    assert(y == x*2)

for (x,y) in [(1,2), (2,4), (3,6)]:
    my_codeblock()

Someone should put in a PEP for this... it seems like these code
blocks could also help to speed up execution in certain circumstances,
since the interpreter doesn't need to create and then dispose of a new
scope for their execution.

And now for something completely different-
    Why not make "def" into an expression that returns a
function/block, instead of a statement? This could obviate lambda by
providing anonymous functions that aren't limited to one line.

e.g.

my_function = def (x,y):
    return sqrt(x**2 + y**2)

my_codeblock = def:
    assert(y == x*2)

(Note- I'm not advocating the replacement of the current syntax, just
an extension) Of course, the indentation requirement might be a
problem when one tries to embed these expressions inside of other
expressions. Not sure how that would work. Semicolons, perhaps, but
then we start to look like Perl :P

-ljp



Relevant Pages

  • Re: Statement local namespaces summary (was Re: python3: where keyword)
    ... The ideas regarding creating blocks whose name bindings affect a different scope ... syntax as well). ... def pre: ... Those semantics don't allow your switch statement example, though, since it ...
    (comp.lang.python)
  • Re: @decorators
    ... What about using the list syntax instead of the @ ... > def foo(): ... Lists are value expressions: not statements, ... > def being valid python but not previously having any effect... ...
    (comp.lang.python)
  • Re: PEP 318 : Def and Class in expressions
    ... I'd prefer it as part of the same expression as the 'def'. ... > syntax does not lend itself well to such twistings. ... The indentation says everything I need ... after the end of the function body. ...
    (comp.lang.python)
  • Re: Is a "real" C-Python possible?
    ... cared about some syntax for properties without any change so far. ... Just look at Stephen Bethards withdrawn PEP 359 in ... def fset: ... foo = propery) ...
    (comp.lang.python)
  • Re: Local Instance Methods
    ... > def f ... I'm not incredibly turned on by that syntax; ... include Baz ... def initialize(moomin, snufkin) ...
    (comp.lang.ruby)