########################################
# The contents of this file are subject to the MLX PUBLIC LICENSE version
# 1.0 (the "License"); you may not use this file except in
# compliance with the License.
# 
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
# the License for the specific language governing rights and limitations
# under the License.
# 
# The Original Source Code is "compClust", released 2003 September 03.
# 
# The Original Source Code was developed by the California Institute of
# Technology (Caltech).  Portions created by Caltech are Copyright (C)
# 2002-2003 California Institute of Technology. All Rights Reserved.
########################################
#
#        Author: Diane Trout
# Last Modified: $Date: 2003/09/05 01:27:40 $
#

"""PickleableLambda provides a convientent way to define functions
that can be stored in pickled files.
"""
import MLab
import Numeric


class PickleableLambda:
  def __init__(self, functionText):
    self._functionText = functionText
    self._function = eval(functionText)
    
  def __call__(self, *args, **kwargs):
    """call function"""
    return apply(self._function,args,kwargs)

  def __getstate__(self):
    return self._functionText
  
  def __setstate__(self, functionText):
    self.__init__(functionText)

# FIXME: Test code (should be TestPickleLambda)
if __name__ == "__main__":
  import cPickle
  square = PickleableLambda("lambda x: x*x")

  print "square(2) = ", square(2)
  cPickle.dump(square, open("pickleTest", 'w'))
  square = None 

  square = cPickle.load(open('pickleTest', 'r'))
  print "square(2) = ", square(2)
  

