I have a dictionary like a class that I use to store some values ββas attributes. I recently added some logic ( __getattr__ ) to return None if the attribute does not exist. As soon as I made this pickle, it crashed, and I wanted to understand why?
Test code:
import cPickle class DictionaryLike(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __iter__(self): return iter(self.__dict__) def __getitem__(self, key): if(self.__dict__.has_key(key)): return self.__dict__[key] else: return None ''' This is the culprit...''' def __getattr__(self, key): print 'Retreiving Value ' , key return self.__getitem__(key) class SomeClass(object): def __init__(self, kwargs={}): self.args = DictionaryLike(**kwargs) someClass = SomeClass() content = cPickle.dumps(someClass,-1) print content
Result:
Retreiving Value __getnewargs__ Traceback (most recent call last): File <<file>> line 29, in <module> content = cPickle.dumps(someClass,-1) TypeError: 'NoneType' object is not callable`
Did I do something stupid? I read a post that deepcopy () might require me to throw an exception if the key does not exist? If so, is there an easy way to achieve what I want without throwing an exception?
End result: if some challenges
someClass.args.i_dont_exist
I want him to return None.
source share