473,614 Members | 2,342 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__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:
"""Introspectio n test"""

#----------------------------------------
def __init__(self,f ilename):
print '** __init__'
self._filename= filename
self._del=' '
self._dirty=Fal se
self._open=Fals e
self._rec=[]
self._recno = 1

#----------------------------------------
def __getattr__(sel f, 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__(sel f, 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 3350
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,f ilename):
print '** __init__'
self._rec=[]
self._fldNames=[]
self._filename= filename
self._del=' '
self._dirty=Fal se
self._open=Fals e
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__(sel f, 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__(sel f, 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__(sel f, 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__(sel f, key, val):
""" Update DBF record values by field name """
print "_sa: %s: %s" % (key, val)
try:

self.__dict__['_rec'][self.__dict__['_fldNames'].index(key.uppe r())] =
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
1400
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 A: # classic! def __getattr__(self, attr): print "-->A.__getattr__"
3
1802
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
6584
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 (unless called explicitely). Here is the exact citation: """ The following methods only apply to new-style classes. __getattribute__( self, name)
13
3487
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
4501
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, it get's intercepted *along with it's argument*, in the same manner as __getattr__ intercepts attributes references for attributes that don't exist. This doesn't quite work: >>> class Foo:
5
2403
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 hints why this is? Example: class decoratorTest(object):
2
5490
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 .... {'age': 40, 'name': 'Zahid'} {'age': 40, 'name': 'Zahid'}
4
3933
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 AttributeError('%s not found in A' % name) def __getattr__(self, name):
7
1706
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 Derived(Base): what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
0
8197
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8142
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8640
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8287
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8443
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4058
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4136
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2573
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.