code suite as first class object ?
bokr at oz.net
Sun Jun 29 00:35:30 CEST 2003
Useless example first:
a = suite:
y = 1
b = suite:
y = 2
a() # equivalent effect to local y = 1 above
(a,b)[bool(x)]() # effect of suite b if bool(x), otherwise suite a
vars()[x]() # succeeds if x in ['a', 'b']
Since binding of the result of suite: is in the form of an assignment, it would also be
possible to create a switch with anonymous suites directly, e.g.,
switch = *2
switch = suite: z = 3
switch = suite: z = 4
or named ones in a chosen directory (of course the name 'switch' has no special status ;-)
shazam['one'] = suite: print 'suite one'
shazam['two'] = suite: print 'suite two'
shazam[suitename]() # or use shazam.get variations if desired
or as attributes?
class NS(object): pass
doatt = NS()
doatt.one = suite: print 'doatt_one'
doatt.two = suite: print 'doatt_two'
(IWT bindings in potentially non-local namespaces would generally require closures,
whereas the vars()[suitename]() usage should not, unless vars() is exported (?)).
The above suites are obviously braindead placeholders. I.e., anything legal as a "suite"
should be legal, including nested suites both old and new (i.e., under e.g., "if expr:"
or "s=suite:") Note that suite: does not introduce a new (name) scope, though one suite object
can be invoked from the body of another. I'm not sure how much new stuff this would
introduce into stack-unwinding for exceptions, but it feels like there ought to be a way
to do better than ignoring suite calls as being internal to a frame ...
Implementation would be a parameterless function which uses the *current* local namespace
as its local space. I.e., no separate frame, just a byte code to execute a local function
(pushing return byte code location) and another to return (popping byte code location and
This would get the performance benefit of sequence indexing or dict lookup vs if/elif/else
equivalents without incurring full function call overhead.
I posted something similar before (not the exception thing ;-), but I think this is a little
better. I haven't thought through the closure issues, but there ought to be a way to handle
Anyone have a real-life example of a long chain of elifs that could be recoded for
BTW, maybe "localfun" or "localcode" or "codeblock" would be better words than "suite"?
Of course, this is just HOTTOMH, so fire away and shoot it full of holes ;-)
Maybe if something survives the flames, it could be useful.
More information about the Python-list