title: How __reduce__ function exactly works in case of pickle module?
body: <p>I don't understand how <code>__reduce__</code> function exactly works in case of <code>pickle</code> module in Python.</p>
  
  <p>Suppose that I have the following class:</p>
  
  <pre><code>class Foo(object):
    def __init__(self, file_name = 'file.txt'):
      self.file_name = file_name
      self.f = open(self.file_name, 'w')
  </code></pre>
  
  <p>It can't be pickled because <code>pickle</code> module doesn't know how to encode file handle:</p>
  
  <pre><code>foo = Foo()
  print(pickle.dumps(foo))
  </code></pre>
  
  <p>Output:</p>
  
  <pre class="lang-none prettyprint-override"><code>TypeError: can't pickle file objects
  </code></pre>
  
  <p>But if I add the <code>__reduce__</code> function it successfully encodes:</p>
  
  <pre><code>import pickle
  
  class Foo(object):
    def __init__(self, file_name = 'file.txt'):
      self.file_name = file_name
      self.f = open(self.file_name, 'w')
  
    def __reduce__(self):
      return (self.__class__, (self.file_name, ))
  
  foo = Foo()
  print(pickle.dumps(foo))
  </code></pre>
  
  <p>Output:</p>
  
  <pre class="lang-none prettyprint-override"><code>c__main__
  Foo
  p0
  (S'file.txt'
  p1
  tp2
  Rp3
  .
  </code></pre>
  
  <p>Am I right that the <code>__reduce__</code> function simply returns "instructions" for the deconstructor to re-create the original object if the <code>pickle.dumps</code> call failed?</p>
  
  <p>It is unclear for me from the documentation.</p>