[Baypiggies] strange behavior with tool inherited from dict.
Max Slimmer
max at SlimmerSoft.com
Wed May 13 03:45:54 CEST 2009
I have a routine I got from Active State cookbook Recipe 361668 ages ago
and have been using it without any problems for literally years. I will
include it below.
I encountered a condition where it doesn't behave normally, but I was
unable to create a "simple" example to show the problem, so have
included some trace to illustrate the problem. Note that emp shown
below is a trimed down version of the emp that failed as I had to
sanitize it a bit.
emp is an instance of the attribute/dictionary class shown below, and
when I try to replace the deds member, using emp.update(a), with an
empty dict it affects emp['deds'] but not emp.deds.
As I said I have never experienced this behavior before, and it appears
only under some conditions. I have been able to fix it by overloading
the update method similar to __init__ assigning self.__dict__ = self.
Any enlightenment on why this is happening (and only sometimes)
thanks,
max
>>> emp
{'sal.rateTyp': 'S', 'clc.fedallow': 0, 'fstnme': 'Patty', 'recnum': 54,
'midini': u'A', 'state_': 'PA', 'deds': {34: {'DEDUCTIONAMOUNT': 10,
'DEDUCTIONCODE': 'K', 'DEDFACTOR': None}}, 'dedsP': [], 'status': 1,
'hertge': 2, 'dteina': datetime.date(1899, 12, 30), 'clc.wrkstate':
'FL', 'clc.stmrtsts': 'M', 'clc.sui': '59', 'dtehre':
datetime.date(1998, 8, 3), 'zipcde': '18042', 'gender': 2, 'payprd': 1,
'sal.payrt1': 875.0, 'clc.fedmrtsts': 'M', 'msc.midini':
u'A', 'taxste': u'PA', 'clc.lvstate': 'PA', 'dtebth':
datetime.date(1976, 7, 9)}
>>> type(emp) # I have named this class adOBJ not attrdict as in
original recipe.
<class 'pytools.adOBJ'>
>>> a = dict(deds={})
>>> emp.deds # get via member name
{34: {'DEDUCTIONAMOUNT': 10, 'DEDUCTIONCODE': 'K', 'DEDFACTOR': None}}
>>> emp.get('deds') # get via dict
{34: {'DEDUCTIONAMOUNT': 10, 'DEDUCTIONCODE': 'K', 'DEDFACTOR': None}}
>>> emp.update(a)
>>> emp.get('deds') # looks like deds is now empty
{}
>>> emp.deds # but it really isn't
{34: {'DEDUCTIONAMOUNT': 10, 'DEDUCTIONCODE': 'K', 'DEDFACTOR': None}}
>>> ??????
class attrdict(dict):
"""A dict whose items can also be accessed as member variables.
>>> d = attrdict(a=1, b=2)
>>> d['c'] = 3
>>> print d.a, d.b, d.c
1 2 3
>>> d.b = 10
>>> print d['b']
10
# but be careful, it's easy to hide methods
>>> print d.get('c')
3
>>> d['get'] = 4
>>> print d.get('a')
Traceback (most recent call last):
TypeError: 'int' object is not callable
"""
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
--
Max Slimmer
email: max at SlimmerSoft.com
More information about the Baypiggies
mailing list