[Python-Dev] Extended Function syntax

Samuele Pedroni pedronis@bluewin.ch
Sun, 2 Feb 2003 23:25:45 +0100


From: "Alex Martelli" <aleax@aleax.it>
> On Sunday 02 February 2003 11:04 pm, Samuele Pedroni wrote:
> > With Guido's 'do': [notice that count is rebindable in the thunk]
> >
> > class iterclose:
> >   def __init__(self,iterwclose):
> >      self.iter = iterwclose
> >
> >   def __call__(self,thunk):
> >      try:
> >        for x in self.iter:
> >          thunk(x)
> >      finally:
> >        self.iter.close()
> >
> > count = 0
> > do iterclose(open('blah.txt')): (line):
> >    if line.find('Python') >=0:
> >      count += 1
> >      print line,
>
> OK -- I *don't* get that " (line):" part, and how calling thunk() in
> iterclose.__init__ binds/rebinds the local (?) variable line of the thunk.
> Looks like black magic to me.  Guess I must just be a bit thick
> tonight -- sorry.

a thunk is like a Smalltalk block, a closure that can rebind the locals and can
get arguments ( (line): above) ),
and maybe non-local returns ( ^ in Smalltalk): in pseudo-python the above is:

count = 0
defClosureAllowingRebinding  _thunk(line):
    if line.find('Python') >=0:
      count += 1
      print line,

iterclose(open('blah.txt'))(_thunk)





> > class autoclose2:
> >   def __init__(self,file):
> >     self.file = file
> >
> >   def __call__(self,thunk):
> >       try:
> >         thunk()
> >       finally:
> >         self.file.close()
> >
> > count = 0
> > myfile = open('blah.txt')
> > do autoclose2(open('blah.txt')):
> >    for line in myfile:
> >      if line.find('Python') >=0:
> >        count += 1
> >        print line,
>
> shouldn't that be "do autoclose2(myfile):" ?  or is there some
> even-blacker magic in this "do" business that I don't get...?
>

yes, you're right.