__getattr__ weirdness

Greg Brunet gregbrunet at NOSPAMsempersoft.com
Fri Aug 22 14:16:02 EDT 2003


In adding the ability to refer to field values using dbfFile.field
notation, I learned how to use __getattr__ and __setattr__ .  After some
trial and error, I got it working.  But as part of my trials, I added
some print statements to debug stuff.  The ones I added to __setattr__
work as expected, but the one in __getattr__ seems to get called just
under 1000 times for every __getattr__ call!

Something is obviously not right here - but I'm at a loss to understand
what's going on.  I've pared down my code to still show it happening &
included it below.  If you run this program & pipe the output to a file,
you'll get just under 14000 debug lines.  Any ideas?  Thanks!

-- 
Greg


# ----------------------------------------------------------------------
----------
class test:
    """Introspection test"""

#----------------------------------------
    def __init__(self,filename):
        print '** __init__'
        self._filename=filename
        self._del=' '
        self._dirty=False
        self._open=False
        self._rec=[]
        self._recno = 1

#----------------------------------------
    def __getattr__(self, key):
        """ Return DBF record values by field name """
        print "_ga: " + key
        try:
            return self._rec[self._fldNames.index(key.upper())]
        except:
            raise AttributeError("Unknown Field: %s" % ( key ))

#----------------------------------------
    def __setattr__(self, key, val):
        """ Update DBF record values by field name """
        print "_sa: %s: %s" % (key, val)
        try:
            self._rec[self._fldNames.index(key.upper())] = val
            print "  (DBF field assignment)"
        except:
            self.__dict__[key] = val    # use the regular variable!
            #raise AttributeError("Unknown Field: %s" % ( key ))

#----------------------------------------
#----------------------------------------
if __name__ == "__main__":

    f = test('test.dbf')
    f._del='*'
    f._recno=123
    f._recno=1
    f._recno=2
    f._recno=3
    f._recno=4
    f._recno=5
    f._recno=6





More information about the Python-list mailing list