Yes!
(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
-ljp