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

前端 未结 4 1096
臣服心动
臣服心动 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 10:48

    Yes, the fact that it's a class member is a problem:

    >>> class Foo():
    ...     Bar = namedtuple('Bar', ['x','y'])
    ...     def baz(self):
    ...         b = Foo.Bar(x=2, y=3)
    ...         print(type(b))
    ...
    >>> a = Foo()
    >>> a.baz()
    
    

    The problem is that when namedtuple() returns a type object, it isn't aware of the fact that it's being assigned to a class member - and thus, it tells the type object that its type name should be __main__.Bar, even though it should really be __main__.Foo.Bar.

提交回复
热议问题