[Python-Dev] Re: Extended Function syntax

Guido van Rossum guido@python.org
Sun, 02 Feb 2003 08:27:21 -0500


[Guido]
> >   switch(expr):
> >     case(val1):
> >       block1
> >     case(val2):
> >       block2
> >     default:
> >       block3
> >
> > This actually makes me worry -- I didn't plan thunks to be the answer
> > to all problems.  A new idea that could cause a paradigm landslide is
> > not necessarily right.

[Samuele]
> I don't exactly get how containment relationships are disambiguated at
> compilation time?
> 
> for sure this is bordering macros' expressivity

I'm not sure I approve of this, but I believe that Glyph's suggestion
can be done by inserting a reference to the most recently active
switch object in the thunk's namespace.  Rough sketch of code:

  class switch:
    def __init__(self, expr):
      self.expr = expr
    def __call__(self, thunk):
      self.success = False
      self.save_switch = thunk.locals.get('__switch__')
      try:
        thunk.locals['__switch__'] = self
        thunk()
      finally:
        thunk.locals['__switch__'] = self.save_switch

  class case:
    def __init__(self, val):
      self.val = val
    def __call__(self, thunk):
      sw = thunk.locals.get('__switch__')
      assert sw is not None
      if sw.success: # A previous case triggered
        return
      if self.val == sw.expr:
        sw.success = True
        thunk()

I'll leave the implementation of default to the reader's imagination.

Again, not endorsing, just playing with Glyph's idea.  Clearly one
could write ugly stuff like

  switch(x):
    print "This is always executed"
    for i in range(10):
      case(i):
        print "x is equal to", i
        case(i+1):
          print "this is unreachable"

--Guido van Rossum (home page: http://www.python.org/~guido/)