Re: Can not dump class object created on runtime

Discussion in 'Python' started by Chris Rebert, Jun 11, 2009.

  1. Chris Rebert

    Chris Rebert Guest

    On Wed, Jun 10, 2009 at 7:25 AM, Metal Zong<> wrote:
    > Hello,
    >
    > Can not dump class object created on runtime.
    >
    > Is there anybody can help me? Thank.
    >
    > Following is testing code:
    >
    > import pickle
    > from new import classobj
    >
    > class A:
    >     def __str__(self):
    >         return self.__class__.name
    >
    > if __name__ == "__main__":
    >     c = classobj('B', (A, ), {}) # create class obj on runtime
    >     print c
    >     print pickle.dumps(c) # get dump string
    >
    > Bellows are outputs:
    >
    > __main__.B
    > Traceback (most recent call last):
    >   File "C:\USERS\train\_work\test\test.py", line 11, in <module>
    >     print pickle.dumps(c)
    >   File "c:\USERS\train\Python25\lib\pickle.py", line 1366, in dumps
    >     Pickler(file, protocol).dump(obj)
    >   File "c:\USERS\train\Python25\lib\pickle.py", line 224, in dump
    >     self.save(obj)
    >   File "c:\USERS\train\Python25\lib\pickle.py", line 286, in save
    >     f(self, obj) # Call unbound method with explicit self
    >   File "c:\USERS\train\Python25\lib\pickle.py", line 748, in save_global
    >     (obj, module, name))
    > pickle.PicklingError: Can't pickle <class __main__.B at 0x00AF4CF0>: it's
    > not found as __main__.B


    pickle stores classes by storing their fully-qualified name (eg.
    "foo.bar.Baz") and NOT by storing the internal Python structures that
    represent the class (as there are apparently various problem
    associated with this). So when it unpickles, it just imports the
    fully-qualified name normally and returns the result of that.
    Since dynamically-created classes have no fully-qualified name, they
    can't be stored this way; hence, you get an exception when trying to
    pickle.dump() them.

    Also, you shouldn't use `classobj` as I believe that's only for
    old-style classes, which are being phased out. Its replacement is the
    built-in `type` metaclass, which creates new-style classes.

    Cheers,
    Chris
    --
    http://blog.rebertia.com
     
    Chris Rebert, Jun 11, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. halfdog
    Replies:
    12
    Views:
    12,583
  2. Ami
    Replies:
    3
    Views:
    439
    Tomás
    Feb 27, 2006
  3. Pedro Ferreira
    Replies:
    1
    Views:
    331
    Pedro Ferreira
    Apr 11, 2008
  4. Trans
    Replies:
    2
    Views:
    320
    Trans
    Jan 29, 2005
  5. Wes Gamble
    Replies:
    1
    Views:
    153
    MenTaLguY
    Mar 7, 2007
Loading...

Share This Page