Python: Can't pickle type X, attribute lookup failed

前端 未结 4 1092
臣服心动
臣服心动 2020-11-28 10:30

I am trying to pickle a namedtuple:

from collections import namedtuple
import cPickle

class Foo:

    Bar = namedtuple(\'Bar\', [\'x\', \'y\'])         


        
4条回答
  •  渐次进展
    2020-11-28 11:00

    Nesting classes makes pickle fail, since it relies on the path of the object inside your application to reconstruct it later.

    The immediate solution is to not nest classes, i.e. move Bar definition to outside Foo. Code will work all the same.

    But a better thing to do is to not use pickle at all to store data. Use some other serialization format, like json, or a database, like sqlite3.

    You have just hit one of the many inconveniences of pickle, if you change your code, move things around, or sometimes make small structural changes, your data becomes unloadable.

    Besides that, pickle has other disadvantages: It is slow, unsecure, python-only...

提交回复
热议问题