__getattr__ weirdness

Hans Nowak hans at zephyrfalcon.org
Fri Aug 22 21:05:43 CEST 2003


Greg Brunet wrote:
> 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!

Sounds like a recursive call.  __getattr__ is only called for attributes that 
are not defined.  For example:

 >>> class Foo:
	def __init__(self):
		self.x = 42
	def __getattr__(self, name):
		print "Aha, trying to access self.%s!" % (name,)
		return None
	
 >>> foo = Foo()
 >>> foo.x  # exists, __getattr__ isn't called
42
 >>> foo.y  # does not exist, __getattr__ is called
Aha, trying to access self.y!

Back to your code:

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

I don't see an attribute self._fldNames here, but I see it here:

#----------------------------------------
     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 ))

Most likely (I didn't actually run the code), this leads to a recursive call of 
__getattr__.  __getattr__ is called, tries to access self._fldNames, which 
doesn't exist, so __getattr__ is called, etc. etc.

Maybe sticking a self._fldNames = something in your __init__ will solve the 
problem.  Then again, maybe you are trying to make that attribute dynamic 
through __getattr__...?

Cheers,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list