[Python-Dev] Extended Function syntax

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


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,

----

class autoclose1:
  def __init__(self,file):
    self.file = file

  def __call__(self,thunk):
      try:
        thunk(self.file)
      finally:
        self.file.close()

count = 0
do autoclose1(open('blah.txt')): (myfile):
   for line in myfile:
     if line.find('Python') >=0: 
      count += 1
      print line,

----

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,