[Python-Dev] PEP 340: Examples as class's.

Ron Adam rrr at ronadam.com
Fri May 6 10:40:10 CEST 2005


Ron Adam wrote:


A minor correction to the Block class due to re-editing.

>     def __call__(self, *args):
>         self.block(*args)
>         self.__del__()

This should have been.

     def __call__(self, *args):
         try:
             self.block(*args)
         except Exception, self.__err__:
             pass
         self.__del__()

Which catches the error in the overriden "block", (I need to change that 
to say "body"), method so it can be re-raised after the "final" method 
is run. The "final" method can handle it if it chooses.

Thanks to Jim Jewett for noticing. It should make more sense now.  :-)


In example (1.), Lock_It lost a carriage return. It should be.

     class Lock_It(Get_Lock):
         def block(self):
             print "Do stuff while locked"

     Lock_It(mylock())()


And example (3.) should be, although it may not run as is...

## 3. A template for committing or rolling back a database:
class Transactional(Block):
     def start(self, db):
         self.db = db
	self.cursor = self.db.cursor()
     def final(self):
         if self.__err__:
             self.db.rollback()
             print "db rolled back due to err:", __err__
             self.__err__ = None
         else:
             db.commit()
     def block(self, batch):
         for statement in batch:
             self.cursor.execute(statement)

statement_batch = [
     "insert into PEP340 values ('Guido','BDFL')",
     "insert into PEP340 values ('More examples are needed')"]
db = pgdb.connect(dsn = 'localhost:pythonpeps')
Transactional(db)(statement_batch)
disconnect(db)

Another Block class could be used for connecting and disconecting.


Cheers, Ron_Adam











More information about the Python-Dev mailing list