Redundant code in multiple methods

Sam Pointon free.condiments at gmail.com
Fri Sep 9 22:09:35 EDT 2005


How about using a class, with __call__, as a wrapper instead of the
function itself?


class FunctionWrapper(object):
    def __init__(self, cls, function):
        self._function = function
        self._cls = cls

    def __call__(self, *args, **kwargs):
         REQUEST = self.REQUEST
        SESSION = REQUEST.SESSION
        dbConnection = self._cls.getDBConnection()
        logger = self._cls.getLogger()
        trackStatsHere()
        # set up some local variables here
        # change some global variables here
        try:
            return self._function(self._cls, *args, **kwargs)
        except:
            raise "handle the error here"
        finally:
            dbConnection.close()

class User(object):
    def __init__(self):
        def View(cls, self, localvariables): #Needs the cls argument
before self to take the FunctionWrapper first argument
            myHtmlDoc = """make the htmldocument here using all
                            of the previous variables"""
            # play with data here
            return myHtmlDoc
    self.View = FunctionWrapper(self, View)

        def Edit(cls, self): #Ditto
            myHtmlDoc = """make the htmldocument here using all
                            of the previous variables"""
            # play with data here
            return myHtmlDoc
    self.Edit = FunctionWrapper(self, Edit)
    
    #the rest of the class




More information about the Python-list mailing list