@@ -20,21 +20,18 @@ class AttribDict(dict):
2020 >>> foo.bar = 1
2121 >>> foo.bar
2222 1
23+ >>> import copy; copy.deepcopy(foo).bar
24+ 1
2325 """
2426
2527 def __init__ (self , indict = None , attribute = None , keycheck = True ):
2628 if indict is None :
2729 indict = {}
2830
29- # Set any attributes here - before initialisation
30- # these remain as normal attributes
31- self .attribute = attribute
32- self .keycheck = keycheck
3331 dict .__init__ (self , indict )
34- self .__initialised = True
35-
36- # After initialisation, setting attributes
37- # is the same as setting an item
32+ self .__dict__ ["_attribute" ] = attribute
33+ self .__dict__ ["_keycheck" ] = keycheck
34+ self .__dict__ ["_initialized" ] = True
3835
3936 def __getattr__ (self , item ):
4037 """
@@ -45,7 +42,7 @@ def __getattr__(self, item):
4542 try :
4643 return self .__getitem__ (item )
4744 except KeyError :
48- if self .keycheck :
45+ if self .__dict__ . get ( "_keycheck" ) :
4946 raise AttributeError ("unable to access item '%s'" % item )
5047 else :
5148 return None
@@ -58,7 +55,7 @@ def __delattr__(self, item):
5855 try :
5956 return self .pop (item )
6057 except KeyError :
61- if self .keycheck :
58+ if self .__dict__ . get ( "_keycheck" ) :
6259 raise AttributeError ("unable to access item '%s'" % item )
6360 else :
6461 return None
@@ -69,14 +66,8 @@ def __setattr__(self, item, value):
6966 Only if we are initialised
7067 """
7168
72- # This test allows attributes to be set in the __init__ method
73- if "_AttribDict__initialised" not in self .__dict__ :
74- return dict .__setattr__ (self , item , value )
75-
76- # Any normal attributes are handled normally
77- elif item in self .__dict__ :
78- dict .__setattr__ (self , item , value )
79-
69+ if "_initialized" not in self .__dict__ or item in self .__dict__ :
70+ self .__dict__ [item ] = value
8071 else :
8172 self .__setitem__ (item , value )
8273
@@ -87,14 +78,12 @@ def __setstate__(self, dict):
8778 self .__dict__ = dict
8879
8980 def __deepcopy__ (self , memo ):
90- retVal = self .__class__ (keycheck = self .keycheck )
81+ retVal = self .__class__ (keycheck = self .__dict__ . get ( "_keycheck" ) )
9182 memo [id (self )] = retVal
9283
93- for attr in dir (self ):
94- if not attr .startswith ('_' ):
95- value = getattr (self , attr )
96- if not isinstance (value , (types .BuiltinFunctionType , types .FunctionType , types .MethodType )):
97- setattr (retVal , attr , copy .deepcopy (value , memo ))
84+ for attr , value in self .__dict__ .items ():
85+ if attr not in ('_attribute' , '_keycheck' , '_initialized' ):
86+ setattr (retVal , attr , copy .deepcopy (value , memo ))
9887
9988 for key , value in self .items ():
10089 retVal .__setitem__ (key , copy .deepcopy (value , memo ))
0 commit comments