473,394 Members | 1,642 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,394 software developers and data experts.

Function Serialization

I want to serialize a function using its pointer. For example
s = """ .... def square(number):
.... return number**2
.... """ functions = {}
exec s in functions
f = functions['square']
f

<function square at 0xb7b5d10c>

Then,
1. Serialize f,
2. Store it into a file a db.

One day later,
3. Retrieve from file or db,
4. Unserialize it
5. Use as it is a normal function, maybe I would set it to an object
with setattr

Any help will be very useful.

Mike

Jul 19 '05 #1
3 2978
The simple way is to use shelve:

$ ipython
Python 2.4.1c2 (#2, Mar 19 2005, 01:04:19)
Type "copyright", "credits" or "license" for more information.

IPython 0.6.5 -- An enhanced Interactive Python.
? -> Introduction to IPython's features.
%magic -> Information about IPython's 'magic' % functions.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import shelve

In [2]: sh=shelve.open("x.shelve")

In [3]: def f(): pass
...:

In [4]: sh["f"]=f

In [5]: sh.close()

In [6]: sh=shelve.open("x.shelve")

In [7]: sh["f"]
Out[7]: <function f at 0xb7d5f614>

You may want to experiment a bit.

Michele Simionato

Jul 19 '05 #2
Michele, thank you for the suggestion, it works as you mention.

But in my case the function is inside a string and I should exec the
string to get the function. Something like this
fields = {}
s = 'def f(): pass'
exec s in fields
f = fields['f']
f <function f at 0xb7a00bfc> import shelve
d = shelve.open('test.db')
d['f'] = f

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/shelve.py", line 129, in __setitem__
p.dump(value)
TypeError: expected string or Unicode object, NoneType found

I am not a pro python developer, so I couldn't understand why it throws
exception. I am a bit confused.

Sincerely,

Mike

Jul 19 '05 #3
By default, shelve uses pickle to serialize objects. Pickle doesn't
actually serialize functions... it just saves the function's name and
name of its defining module, and upon loading attempts to find that
function again. This is pretty much /never/ going to work the way you
want it to if you're using exec.

If you really want to save a function, you're going to have to save its
source code and exec it upon reloading. I think the best way to
achieve this would be to make your own wrapper class which defines a
__call__ method and implements custom pickling routines (see the pickle
documentation for how to do this). You could probably even make it
into a decorator, but I wouldn't know about that since I'm stuck with
Python 2.3.

It would look something like this

def f(): pass
f = SerializableFunction(f)

where SerializableFunction is defined as:

class SerializableFunction(object):
def __init__(self, function):
self.function = function

def __call__(self, *args, **keywords):
return self.function(*args, **keywords)

# custom pickle routines
def __getnewargs__(self):
...
def __getstate__(self):
# extract function source
...
def __setstate__(self):
...

You can use the inspect module to get function source code, although
AFAIK it's impossible to get source from functions defined in the
interactive interpreter.

Jul 19 '05 #4

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

Similar topics

37
by: Ben | last post by:
Hi, there. Recently I was working on a problem where we want to save generic closures in a data structure (a vector). The closure should work for any data type and any method with pre-defined...
1
by: andrewcw | last post by:
There is an error in XML document (1, 2). I used XML spy to create the XML and XSD. When I asked to have the XML validated it said it was OK. I used the .net SDK to generate the class. I have...
3
by: Aaron Clamage | last post by:
Hi, I'm not sure that if this is the right forum, but any help would be greatly appreciated. I am porting some java serialization code to c# and I can't figure out the correct way to do it. ...
3
by: Alexander | last post by:
When i store rule on PC with .NET.SP1 i cant restore them from PC without SP1. An i get this Error: System.Runtime.Serialization.SerializationException: Possible Version mismatch. Type...
5
by: rolandz | last post by:
Hi, Maybe somebody has been fighting with the problem that I do, currently. I have a class that has method f(). The two versions of the f() method accept different objects: Int and Short. These...
4
by: mijalko | last post by:
Hi, I have inherited my class from System.Drawing.Printing.PrintDocument and I wish to serialize this object using XmlSerializer. And I get exception "There was an error reflecting type ...". If I...
5
by: Nikola Skoric | last post by:
I ran in Mono a program developed on .NET Framework 2.0 and it ran OK until I tried to desirialize a object. There the program died abruptly dumping this: System.ArgumentOutOfRangeException:...
0
by: bharathreddy | last post by:
Before going to that i want to say few thing on serialization : Serialization is the process of converting an object into a form that can be readily transported. For example, you can serialize an...
1
by: kikisan | last post by:
I am developing a windows service which utilizes the following classes: interface IPersistable; abstract class PersistableObject : IPersistable;
2
by: mkvenkit.vc | last post by:
Hello, I hope this is the right place to post a question on Boost. If not, please let me know where I can post this message and I will do so. I am having a strange problem with std::string as...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...

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.