title: How to pickle functions/classes defined in __main__ (python)
body: <p>I would like to be able to pickle a function or class from within __main__, with the obvious problem (mentioned in other posts) that the pickled function/class is in the __main__ namespace and unpickling in another script/module will fail.</p>
  
  <p>I have the following solution which works, is there a reason this should not be done?</p>
  
  <p>The following is in myscript.py:</p>
  
  <pre><code>import myscript
  import pickle
  
  if __name__ == "__main__":               
  
      print pickle.dumps(myscript.myclass())
  
  else:
  
      class myclass:
          pass
  </code></pre>
  
  <p><strong>edit</strong>: The unpickling would be done in a script/module that <em>has access to</em> myscript.py and can do an <code>import myscript</code>.  The aim is to use a solution like <a href="http://www.parallelpython.com/" rel="noreferrer" title="parallel python">parallel python</a> to call functions remotely, and be able to write a short, <em>standalone</em> script that contains the functions/classes that can be accessed remotely.</p>