__getattr__ weirdness

Greg Brunet gregbrunet at NOSPAMsempersoft.com
Fri Aug 22 16:29:08 EDT 2003


"Stephan Diehl" <stephan.diehl at gmx.net> wrote in message
news:bi5ofn$uo3$04$1 at 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






More information about the Python-list mailing list