Code blocks
David Mertz
mertz at gnosis.cx
Tue Oct 14 00:38:06 EDT 2003
|> block foo(this, that, other):
|> x = this+that
|> y = this*other
|> z = x // (y-that)
|> def bar(someblock):
|> a, b, c = (4, 5, 6)
|> someblock(a,b,c)
|> return x,y,z
|> vals = bar(foo) #-> (9, 24, 0)
|Anyway, now that i think about this, it should be possible to lookup
|the calling context's locals and insert the current locals.
| def foo():
| absorb()
| x = this+that
| y = this*other
| z = x // (y-that)
| expose()
It's not too hard to look up the call stack to GET the binding from the
calling context. I.e.
>>> def about_caller():
... import inspect
... print inspect.currentframe(1).f_locals
...
>>> def somefunc():
... x, y, z = 1, 2, 3
... about_caller()
...
>>> somefunc()
{'y': 2, 'x': 1, 'z': 3}
Actually, you could define this in a utility 'absorb()' function (which
would look at 'currentframe(2)' instead of 1). The problem is that
there's no good way to put values back INTO the calling context. So I
can't see a way to write the 'expose()' function.
Btw. In answer to Alex' concern about dynamic scoping--which admittedly
my suggestion basically amounts to: I think the main use of a "block"
(or whatever name might be used) is that certain code might be used
between many local contexts. If you just define a block within a
particular function 'spam()', that hardly helps you when you want to do
the same steps in 'eggs()'.
In a way, a block amounts to a poor-man's macro, since it IS an
expansion of sorts. But to my mind, it isn't nearly as dangerous as
macros can be. Then again, as I proposed it, it might be non-obvious
when a call is to a block versus when it is to a function. So maybe
some special syntax would be needed at the point of the call also.
Of course, as I envision it, a block might also do a bit of inspection
of its context (as in the 'about_caller()' function above)... so maybe
it really is skating too close to the perils of macros, which Alex and I
pretty much agree on.
Yours, David...
--
mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o
gnosis _/_/ Postmodern Enterprises \_\_
.cx _/_/ \_\_ d o
_/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e
More information about the Python-list
mailing list