Is there a better way of coding this?

Edward C. Jones edcjones at erols.com
Sun Jun 1 11:40:54 EDT 2003


I wrote the following code so the writer of "Fgeti" could ignore some 
subtle error processing. Can this code be rewritten without the template 
and the exec? Perhaps using the "curry" class below?

Thanks,
Ed Jones

-----------------------------------------------------------------

template ="""\
def <@getname@>(self):
     # Subtle error processing here.
     self.<@truename@> = self.<@funname@>(self.data)
     return self.<@truename@>

<@attrname@> = property(<@getname@>, None, None)
"""

def makeget(getname, truename, funnanme, attrname):
     text = template.replace('<@getname@>', getname)
     text = text.replace('<@truename@>', truename)
     text = text.replace('<@funname@>', funnanme)
     return text.replace('<@attrname@>', attrname)

class X(object):
     exec makeget('geti', '_i', 'Fgeti', 'i')

     def __init__(self):
         self.data = 7

     def Fgeti(self, i):
         return 2*i

x = X()
print x.i
print x.__dict__

-----------------------------------------------------------------

# A curry class from the net.
class curry:
     def __init__(self, fun, *args, **kwargs):
         self.fun = fun
         self.pending = args[:]
         self.kwargs = kwargs.copy()

     def __call__(self, *args, **kwargs):
         if kwargs and self.kwargs:
             kw = self.kwargs.copy()
             kw.update(kwargs)
         else:
             kw = kwargs or self.kwargs

         return self.fun(*(self.pending + args), **kw)





More information about the Python-list mailing list