Is there a better way of coding this?

Sean Ross sross at connectmail.carleton.ca
Sun Jun 1 18:01:25 CEST 2003


Have a look at this recipe for automating the creation of simple readonly,
writeonly, or read and write properties.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768

You can also find a metaclass implementation here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197965

These should give you some ideas. Have fun.
Sean

"Edward C. Jones" <edcjones at erols.com> wrote in message
news:bbd6so$4sb$1 at bob.news.rcn.net...
> 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