473,386 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Pickling a class with a __getattr__

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
>>import cPickle as pickle
class Dict(dict):
.... pass
....
>>>

friend = Dict(name='Zahid', age=40)
friend
{'age': 40, 'name': 'Zahid'}
>>v=pickle.dumps(friend)
p=pickle.loads(v)
p
{'age': 40, 'name': 'Zahid'}

This is what happens when I'm trying to be clever:
>>import cPickle as pickle
class Dict(dict):
.... def __getattr__(self, key):
.... return self.__getitem__(key)
....
>>friend = Dict(name='Zahid', age=40)
friend
{'age': 40, 'name': 'Zahid'}
>>friend.name
'Zahid'
>>v=pickle.dumps(friend)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/copy_reg.py", line 73, in _reduce_ex
getstate = self.__getstate__
File "<stdin>", line 3, in __getattr__
KeyError: '__getstate__'
Why can't I pickle the slightly more featurefull class there called
'Dict'? I've got my reasons for not going for a simple type dict but
feel that that is irrelevant right now.

Apr 1 '07 #1
2 5440
Peter Bengtsson wrote:
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 is what happens when I'm trying to be clever:
>>>import cPickle as pickle
class Dict(dict):
... def __getattr__(self, key):
... return self.__getitem__(key)
...
>>>friend = Dict(name='Zahid', age=40)
friend
{'age': 40, 'name': 'Zahid'}
>>>friend.name
'Zahid'
>>>v=pickle.dumps(friend)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/copy_reg.py", line 73, in _reduce_ex
getstate = self.__getstate__
File "<stdin>", line 3, in __getattr__
KeyError: '__getstate__'
Why can't I pickle the slightly more featurefull class there called
'Dict'?
Because you allow your __getattr__() implementation to raise the wrong kind
of exception.
>>from cPickle import dumps, loads
class Dict(dict):
.... def __getattr__(self, key):
.... try:
.... return self[key]
.... except KeyError:
.... raise AttributeError
....
>>friend = Dict(name="Zaphod", age=42)
v = dumps(friend)
p = loads(v)
p
{'age': 42, 'name': 'Zaphod'}

Peter
Apr 1 '07 #2
On Apr 1, 5:48 pm, Peter Otten <__pete...@web.dewrote:
Peter Bengtsson wrote:
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 is what happens when I'm trying to be clever:
>>import cPickle as pickle
class Dict(dict):
... def __getattr__(self, key):
... return self.__getitem__(key)
...
>>friend = Dict(name='Zahid', age=40)
friend
{'age': 40, 'name': 'Zahid'}
>>friend.name
'Zahid'
>>v=pickle.dumps(friend)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/copy_reg.py", line 73, in _reduce_ex
getstate = self.__getstate__
File "<stdin>", line 3, in __getattr__
KeyError: '__getstate__'
Why can't I pickle the slightly more featurefull class there called
'Dict'?

Because you allow your __getattr__() implementation to raise the wrong kind
of exception.
>from cPickle import dumps, loads
class Dict(dict):

... def __getattr__(self, key):
... try:
... return self[key]
... except KeyError:
... raise AttributeError
...>>friend = Dict(name="Zaphod", age=42)
>v = dumps(friend)
p = loads(v)
p

{'age': 42, 'name': 'Zaphod'}

Peter
Thanks! That did the trick. I also noticed that I could define
__getstate__ and __setstate__ (needed for protocol 2) but your
solution works much better.

Apr 1 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Gabriel Genellina | last post by:
Hi In the following code sample, I have: - a Worker class, which could have a lot of methods and attributes. In particular, it has a 'bar' attribute. This class can be modified as needed. - a...
3
by: Nicolas Fleury | last post by:
Hi, Does anyone know if arrays would be picklable in python 2.4? Until then, I tried to derive from array.array and add __setstate__ and __getstate__ with the following code, but it seems I'm not...
20
by: syd | last post by:
In my project, I've got dozens of similar classes with hundreds of description variables in each. In my illustrative example below, I have a Library class that contains a list of Nation classes. ...
8
by: Hans Georg Krauthaeuser | last post by:
Dear all, I have a long running application (electromagnetic compatibility measurements in mode-stirred chambers over GPIB) that use pickle (cPickle) to autosave a class instance with all the...
1
by: fedor | last post by:
Hi all, happy new year, I was trying to pickle a instance of a subclass of a tuple when I ran into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should I rewrite my class so I can...
9
by: Alex | last post by:
I have a serious problem and I hope there is some solution. It is easier to illustrate with a simple code: >>> class Parent(object): __slots__= def __init__(self, a, b): self.A=a; self.B=b...
0
by: Irmen de Jong | last post by:
I'm having troubles pickling classes that extend Exception. Given the following source: class Foo(object): def __init__(self, m): self.m=m class Bar(Exception): def __init__(self, m):
0
by: Magnus Schuster | last post by:
With this explanation the behaviour is absolutely clear. Can I find some documentation anywhere containing more background information how magic functions are resolved? I haven't been successful...
11
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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...
0
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,...

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.