title: Python: Can't pickle type X, attribute lookup failed
body: <p>I am trying to pickle a <code>namedtuple</code>:</p>
  
  <pre><code>from collections import namedtuple
  import cPickle
  
  class Foo:
  
      Bar = namedtuple('Bar', ['x', 'y'])
  
      def baz(self):
          s = set()
          s.add(Foo.Bar(x=2, y=3))
          print cPickle.dumps(s)
  
  if __name__ == '__main__':
      f = Foo()
      f.baz()
  </code></pre>
  
  <p>This produces the following output:</p>
  
  <pre><code>Traceback (most recent call last):
    File "scratch.py", line 15, in &lt;module&gt;
      f.baz()
    File "scratch.py", line 11, in baz
      print cPickle.dumps(s)
  cPickle.PicklingError: Can't pickle &lt;class '__main__.Bar'&gt;: attribute lookup __main__.Bar failed
  </code></pre>
  
  <p>What am I doing wrong? Is the problem that <code>Bar</code> is a member of <code>Foo</code>? (Moving the definition of <code>Bar</code> to the top level solves the problem, although I'm still curious why this happens.)</p>