FAQ
In article <slrnc7ot1r.3r8.joe at gate.notcharles.ca>,
Joe Mason wrote:
In article <f70e3538.0404131305.52d7c708 at posting.google.com>, Lonnie
Princehouse wrote:
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()
What's the point? If you've got to make a named item before the for
loop anyway, why not just use a function? The point of code blocks is
to be anonymous, and declared inline.

Joe
Is it?

Or is the point of the codeblock to execute in the same scope as where
it is called (i.e., dynamic scoping).

It's fairly easy to emulate the anonymous part (by not having it inline,
and just using a dummy name, which makes it less anonymous), but it's
much harder to emulate the dynamic scoping (though with some magic of
the stack frame it could probably be done, but it might be pretty ugly).

Dynamic scoping be partially simulated easily enough:

def block(b):
import sys
caller_frame = sys._getframe().f_back
exec b.func_code in caller_frame.f_locals

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

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


(note that this won't actually work since you can't exec a function with
"free variables", so obviously the "injection" in block would need to be
a bit more clever - perhaps building a code object dynamically).

It may be possible to use function decorater to achieve the dynamic
scoping nature (and thus achieving one of those goals without having to
make further changes to the python "core" like changing the grammar
would):

def test():
def my_codeblock() [block]:
assert(y == x * 2)

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

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

People

Translate

site design / logo © 2022 Grokbase