473,387 Members | 1,516 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

__getattr__ weirdness

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

Jul 18 '05 #1
3 3331
I've figured out one thing: that be re-arranging the __init__ code
assignments (and adding one that was placed later in code I snipped
out), I am able to get the extra _ga calls to stop a lot earlier. This
code:

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

.... by assigning _rec & _fldNames first, gets the repeated _ga calls to
stop after the first assignment following those two assignments. I'm
still at a loss as to why _ga is being called all these times to begin
with though! I'm only assigning values, not requesting them! Thanks,

--
Greg

Jul 18 '05 #2
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!

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!


Within the __getattr__ method, you can't just do normal attribute access as
this will trigger another call to __getattr__, so you where stuck in an
infinite loop.
try to access the required attribute directly from the __dict__

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

Hope that helps

Stephan
Jul 18 '05 #3
"Stephan Diehl" <st***********@gmx.net> wrote in message
news:bi*************@news.t-online.com...
Within the __getattr__ method, you can't just do normal attribute access as this will trigger another call to __getattr__, so you where stuck in an infinite loop.
try to access the required attribute directly from the __dict__

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

Hope that helps

Stephan


Hey Stephan:

That did the trick! Actually, I had to do the same for self._fldNames
as well. Also, I changed them in the _sa code section instead of the
_ga code, since now that I look at it again with a little better
understanding, the original _sa code was referring to the _rec &
_fldNames variables/attributes directly, so as long as they weren't
defined, it was triggering the _ga calls. So now the _ga code doesn't
get called unless I specifically ask for it - like I would want. The
code now looks like:

#----------------------------------------
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.__dict__['_rec'][self.__dict__['_fldNames'].index(key.upper())] =
val
print " (DBF field assignment)"
except:
self.__dict__[key] = val # use the regular variable!
#raise AttributeError("Unknown Field: %s" % ( key ))

Thanks for everyone's help!

--
Greg
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Holger Joukl | last post by:
Hi there, please excuse my rather lengthy post. With introduction of the new style classes, something seems to have changed for __getattr__ hooks, even for classic classes: getattr.py: class...
3
by: Chris Curvey | last post by:
Hi all, I have this program class Company: def __init__(self, revenues, costs): self.revenues = revenues self.costs = costs def __getattr__(self, name):
0
by: Gigi | last post by:
Hi, In the Python documentation regarding __getattribute__ (more attribute access for new style classes) it is mentioned that if __getattribute__ is defined __getattr__ will never be called...
13
by: Pelmen | last post by:
How can I get rid of recursive call __getattr__ inside this method, if i need to use method or property of the class?
6
by: Erik Johnson | last post by:
Maybe I just don't know the right special function, but what I am wanting to do is write something akin to a __getattr__ function so that when you try to call an object method that doesn't exist,...
5
by: glomde | last post by:
Hi, I tried to write a decorator for that should be for methods but for some reasons it doens seem to work when you try to do it on the __getattr__ method in a class. Could anybody give some...
2
by: Peter Bengtsson | last post by:
Hi, I'm trying to pickle an object instance of a class that is like a dict but with a __getattr__ and I'm getting pickling errors. This works but is not good enough. $ python2.4 .... pass...
4
by: Enrico | last post by:
Hi there, I have the following situation (I tryed to minimize the code to concentrate on the issue): def __getattr__(self, name): print 'A.__getattr__' if name == 'a': return 1 raise...
7
by: =?UTF-8?Q?Alexandru_Mo=C8=99oi?= | last post by:
i'm facing the following problem: class Base(object): def __getattr__(self, attr): return lambda x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.