Is there a better way of coding this?

Anders J. Munch andersjm at inbound.dk
Sun Jun 1 12:40:56 EDT 2003


"Edward C. Jones" wrote:
> 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?

Yes.  Use getattr, setattr and a nested function.  Something like
this:

# very much untested code follows:
def makeprop(getname, truename, funnanme):
    def fget(self):
        # Subtle error processing here.
        setattr(self, truename, getattr(self, funname)(self.data))
        return getattr(self, truename)
    return property(fget, None, None)

class X(object):
    i = makeprop('geti', '_i', 'Fgeti')
    ...

- Anders







More information about the Python-list mailing list