473,785 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to better pickle an extension type

I would like to pickle an extension type (written in pyrex). I have
it working thus far by defining three methods:

class C:
# for pickling
__getstate__(se lf):
... # make 'state_obj'
return state_obj

__reduce__(self ):
return C,(args,to,__in it__),me.__gets tate__()

# for unpickling
__setstate__(se lf,state_obj):
self.x=state_ob j.x
...
This gets the class pickling and unpickling.

However, I'd like to not specify arguments for __init__ (as I do now
in __reduce__), and so not have __init__ invoked during unpickling.

I would like to have the pickling machinery somehow create an
uninitialized object, and then call its __setstate__, where I can re-
create it from 'state_obj'.

Is there a kosher way to do so, that is without me having to have a
special mode in the constructor for when the object is being created
by the unpickler?

Apr 16 '07 #1
3 4511
dgdev <dg*******@yaho o.comwrote:
I would like to pickle an extension type (written in pyrex). I have
it working thus far by defining three methods:

class C:
# for pickling
__getstate__(se lf):
... # make 'state_obj'
return state_obj

__reduce__(self ):
return C,(args,to,__in it__),me.__gets tate__()

# for unpickling
__setstate__(se lf,state_obj):
self.x=state_ob j.x
...
This gets the class pickling and unpickling.

However, I'd like to not specify arguments for __init__ (as I do now
in __reduce__), and so not have __init__ invoked during unpickling.

I would like to have the pickling machinery somehow create an
uninitialized object, and then call its __setstate__, where I can re-
create it from 'state_obj'.

Is there a kosher way to do so, that is without me having to have a
special mode in the constructor for when the object is being created
by the unpickler?
I don't understand why you have a problem -- __init__ is NOT called by
default upon loading an object w/__setstate__. Witness:
>>class C(object):
.... def __init__(self, *a): print 'init', a
.... def __getstate__(se lf): print 'gs'; return {}
.... def __setstate__(se lf, *a): print 'ss', a
....
>>c = C()
init ()
>>s = cPickle.dumps(c , 2)
gs
>>s
'\x80\x02c__mai n__\nC\nq\x01)\ x81q\x02}b.'
>>z = cPickle.loads(s )
ss ({},)
Perhaps you're not using protocol 2? You should be...
Alex
Apr 17 '07 #2
dgdev wrote:
I would like to pickle an extension type (written in pyrex). I have
it working thus far by defining three methods:

class C:
# for pickling
__getstate__(se lf):
... # make 'state_obj'
return state_obj

__reduce__(self ):
return C,(args,to,__in it__),me.__gets tate__()

# for unpickling
__setstate__(se lf,state_obj):
self.x=state_ob j.x
...

This gets the class pickling and unpickling.

However, I'd like to not specify arguments for __init__ (as I do now
in __reduce__), and so not have __init__ invoked during unpickling.

I would like to have the pickling machinery somehow create an
uninitialized object, and then call its __setstate__, where I can re-
create it from 'state_obj'.

Is there a kosher way to do so, that is without me having to have a
special mode in the constructor for when the object is being created
by the unpickler?
Why are you overwriting the __reduce__() method? The default
object.__reduce __() method, inherited by all new style classes,
already does what you want. If you really must overwrite it, and
you don't want __init__() to get called, then you should return a
reconstructor named __newobj__() as the first item of reduce
tuple. Something like this:
>>def __newobj__(cls, *args):
.... return cls.__new__(cls , *args)
....
>>class C(object):
.... def __init__(self):
.... print "I shouldn't be called at reconstruction"
.... def __reduce__(self ):
.... try:
.... getnewargs = self.__getnewar gs__
.... except AttributeError:
.... newargs = (self.__class__ ,)
.... else:
.... newargs = (self.__class__ ,) + getnewargs()
.... try:
.... getstate = self.__getstate __
.... except AttributeError:
.... # this ignores __slots__ complications
.... state = self.__dict__
.... else:
.... state = getstate()
.... # this ignores list and dict subclasses
.... return __newobj__, newargs, state
....
>>c = C()
I shouldn't be called at reconstruction
>>import pickle
for proto in range(3):
.... assert isinstance(pick le.loads(pickle .dumps(c, proto)), C)
....
>>>
Ziga

Apr 17 '07 #3
Thanks for your replies.

The code I showed above was pyrex code, not python code. You are
correct that python objects do not require .__reduce__() to be
picklable, but apparently c extension types do (makes sense, they must
be more opaque to the python machinery).

I'll try the .__newobj__(), see if I can get it to do what I want...

On Apr 17, 2:50 am, Ziga Seilnacht <ziga.seilna... @gmail.comwrote :
dgdev wrote:
I would like topicklean extension type (written inpyrex). I have
it working thus far by defining three methods:
class C:
# for pickling
__getstate__(se lf):
... # make 'state_obj'
return state_obj
__reduce__(self ):
return C,(args,to,__in it__),me.__gets tate__()
# for unpickling
__setstate__(se lf,state_obj):
self.x=state_ob j.x
...
This gets the class pickling and unpickling.
However, I'd like to not specify arguments for __init__ (as I do now
in __reduce__), and so not have __init__ invoked during unpickling.
I would like to have the pickling machinery somehow create an
uninitialized object, and then call its __setstate__, where I can re-
create it from 'state_obj'.
Is there a kosher way to do so, that is without me having to have a
special mode in the constructor for when the object is being created
by the unpickler?

Why are you overwriting the __reduce__() method? The default
object.__reduce __() method, inherited by all new style classes,
already does what you want. If you really must overwrite it, and
you don't want __init__() to get called, then you should return a
reconstructor named __newobj__() as the first item of reduce
tuple. Something like this:
>def __newobj__(cls, *args):

... return cls.__new__(cls , *args)
...>>class C(object):

... def __init__(self):
... print "I shouldn't be called at reconstruction"
... def __reduce__(self ):
... try:
... getnewargs = self.__getnewar gs__
... except AttributeError:
... newargs = (self.__class__ ,)
... else:
... newargs = (self.__class__ ,) + getnewargs()
... try:
... getstate = self.__getstate __
... except AttributeError:
... # this ignores __slots__ complications
... state = self.__dict__
... else:
... state = getstate()
... # this ignores list and dict subclasses
... return __newobj__, newargs, state
...>>c = C()

I shouldn't be called at reconstruction> >importpickle
>for proto in range(3):

... assert isinstance(pick le.loads(pickle .dumps(c, proto)), C)
...

Ziga

Apr 18 '07 #4

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

Similar topics

2
2437
by: Andrew Degtiariov | last post by:
Hello! I tried to rewrite my python module in C. My module is successfully imported but i can't assing anything to class attributes (tp_setattr in PyTypeObject for class FlowReportRow filled up by pointer to FlowReportRowObjectSetAttr function and printf in ones show the function does not called) Where I was mistaken? (you may see the module sources at http://astral.ua/~ad/Report.c) I wrote simple test:
6
3075
by: gregory lielens | last post by:
Hello, I am currently writing python bindings to an existing C++ library, and I just encountered a problem that I hope has been solved by more experienced python programmers: A C++ class (let's call it CClass) is binded using classical Python extension API to _PClass, which is accesible through python without any problem. The problem is that I want this class to be extended/extensible in python, and expose the python-extended version...
4
1790
by: harold fellermann | last post by:
Hi all, I have a problem pickling an extension class. As written in the Extending/Embedding Manual, I provided a function __reduce__ that returns the appropreate tuple. This seams to work fine, but I still cannot pickle because of the following error: >>> from model import hyper >>> g = hyper.PeriodicGrid(4,4,1)
0
1117
by: Pedro Werneck | last post by:
Hi list I'm trying to implement a new type in a C extension and it must support some binary operators, like &, |, ^, << and >>. With &, | and ^, the method must receive another object of the same type, perform the operation with an attribute of both, create a new object with the result as the attribute and return it. Everything works perfectly with &, | and ^, but with << and >> I need
2
2646
by: Stephanie Stowe | last post by:
Hi. I have been having trouble getting one of a customer's production servers to respond to a SOAP request the way the other server does (properly, that is). After much cluelessness due to the lack of SOAP knowledge, I have figured out how to get the actual error that is occuring: Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below...
1
2048
by: jiba | last post by:
Hi all, I'm currently working on a secure Pickle-like module, Cerealizer, http://home.gna.org/oomadness/en/cerealizer/index.html Cerealizer has a pickle-like interface (load, dump, __getstate__, __setstate__,...), however it requires to register the class you want to "cerealize", by calling cerealizer.register(YourClass). Cerealizer doesn't import other modules (contrary to pickle), and the only methods it may call are...
3
3614
by: Iljya | last post by:
Hello, I need to pickle the type numpy.float32 but encounter an error when I try to do so. I am able to pickle the array itself, it is specifically the type that I cannot pickle. I am using: Numpy version: 0.9.4 Python version: 2.4.3 Windows XP
1
2426
by: gregory.lielens | last post by:
Hello, We are currently writing python bindings to an existing C++ library, and we encountered a problem that some of you may have solved (or that has found unsolvable :( ): A C++ class (let's call it CClass) is binded using classical Python extension API to _PClass, which is accesible through python without any
2
2795
by: Paul Moore | last post by:
I'm trying to implement an extension type with a power operator. The operator is unusual in that I want to allow my objects to be raised to an integer power: p = Pattern() p3 = p ** 3 I've implemented the code for a nb_power slot, it converts the "other" argument to a C long using PyInt_AsLong().
0
9645
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.