title: Python: determine actual current module (not __main__)
body: <p>I'm trying to determine the actual current module of a function (as seen if imported from elsewhere), even if the current module is the "<a href="http://docs.python.org/library/__main__.html" rel="noreferrer">top level scripting environment</a>" <code>__main__</code>.</p>
  
  <p>It may sound like a weird thing to do, but the background is that I need to serialize a function and unserialize it (including arguments) on a different machine, for which I need to make sure the correct module AND NOT <code>__main__</code> is imported before deserializing (otherwise I get an error saying <code>AttributeError: 'module' object has no attribute my_fun</code>).</p>
  
  <p>So far, I've tried <a href="https://stackoverflow.com/questions/1106840/find-functions-explicitly-defined-in-a-module-python">inspection</a>:</p>
  
  <pre><code>import inspect
  print inspect.getmodule(my_fun)
  </code></pre>
  
  <p>which gives me </p>
  
  <pre><code>&lt;module '__main__' from 'example.py'&gt;
  </code></pre>
  
  <p>of course. I also tried finding something useful using <code>globals()</code>, no luck.</p>
  
  <p>What I really want is <code>&lt;module 'example' from 'example.py'&gt;</code>. I suppose a hacky way would be to parse it from the file name using something like </p>
  
  <pre><code>m_name = __main__.__file__.split("/")[-1].replace(".pyc","")
  </code></pre>
  
  <p>and then find the module by name <code>sys.modules[m_name]</code>.</p>
  
  <p>Is there a cleaner/better way to do this?</p>
  
  <p>EDIT:
  After learning about ipython's "FakeModule" and a bit more googling, I came accross <a href="https://stackoverflow.com/questions/3431419/how-to-get-unpickling-to-work-with-ipython">this post</a>, which describes exactly the problem that I'm facing, including my current solution to it (which is explicitly importing the current module <code>import current_module</code> and serializing <code>current_module.my_fun</code> instead of my_fun). I'm trying to avoid this, as it might not be intuitive for the users of my package.</p>