pythonpython-moduleinspection

Python: determine actual current module (not __main__)


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 "top level scripting environment" __main__.

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 __main__ is imported before deserializing (otherwise I get an error saying AttributeError: 'module' object has no attribute my_fun).

So far, I've tried inspection:

import inspect
print inspect.getmodule(my_fun)

which gives me

<module '__main__' from 'example.py'>

of course. I also tried finding something useful using globals(), no luck.

What I really want is <module 'example' from 'example.py'>. I suppose a hacky way would be to parse it from the file name using something like

m_name = __main__.__file__.split("/")[-1].replace(".pyc","")

and then find the module by name sys.modules[m_name].

Is there a cleaner/better way to do this?

EDIT: After learning about ipython's "FakeModule" and a bit more googling, I came accross this post, which describes exactly the problem that I'm facing, including my current solution to it (which is explicitly importing the current module import current_module and serializing current_module.my_fun instead of my_fun). I'm trying to avoid this, as it might not be intuitive for the users of my package.


Solution

  • I actually ran across this same problem.

    What I used was:

    return os.path.splitext(os.path.basename(__main__.__file__))[0]
    

    Which is effectively the same as your "hack." Honestly, I think its the best solution.