problem pickling objects created with the type function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • danny

    problem pickling objects created with the type function

    Howdy,

    I've run into a problem pickling objects created with a type
    statement. Here's the code:

    *************** *************** ***************
    import pickle

    class foo(object):
    def __init__(self):
    self.wombat = []

    def setWombat(self) :
    self.wombat = [1]

    # pickle a foo instance
    x = foo()
    print pickle.dumps(x) # works

    # pickle a foobar instance
    childType = type('foobar',( foo,),{'slor':7 })
    y = childType()
    print pickle.dumps(y) # raises an exception
    *************** *************** ***************

    I'm pretty sure the failure is because 'foobar' is never in the global
    namespace. If I change the code to foobar = type('foobar',. .. then
    the code works, but I dont' want to do this because I create the class
    name in a factory and it is mangled to prevent different invocations
    of the factory from having the same class name.

    Does anyone know how to get around this, or how to get 'foobar' =
    childType into the global namespace?

    thanks,
    Danny
  • Jeff Epler

    #2
    Re: problem pickling objects created with the type function

    Yep.

    Pickle stores instances by pickling information about the instance, plus
    a string it uses to find the class.

    If you do something too clever, like you did above, it doesn't work.

    Jeff

    Comment

    • Greg Chapman

      #3
      Re: problem pickling objects created with the type function

      On 21 Apr 2004 14:57:17 -0700, danny_shevitz@y ahoo.com (danny) wrote:
      [color=blue]
      >I'm pretty sure the failure is because 'foobar' is never in the global
      >namespace. If I change the code to foobar = type('foobar',. .. then
      >the code works, but I dont' want to do this because I create the class
      >name in a factory and it is mangled to prevent different invocations
      >of the factory from having the same class name.
      >
      >Does anyone know how to get around this, or how to get 'foobar' =
      >childType into the global namespace?[/color]

      You should be able to make foobars pickleable without introducing foobar into
      the global namespace by using a __reduce__ method, see:

      Pickling new-style objects in Python 2.2 is done somewhat clumsily and causes pickle size to bloat compared to classic class instances. This PEP documents a new pickle protocol in Python 2.3 that takes care of this and many other pickle issues.


      expecially the section "Extended __reduce__ API".

      ---
      Greg Chapman

      Comment

      Working...