rocky rocky - 11 months ago 51
Python Question

Given frame or code object, how do I get the associated module file loaded

In a debugger I would like to verify that the source path matches the code that is running. One way to do this in Python 3 is to look at the module byte-compiled file (a

) which has a field for the source size modulo

So now the question is given a frame object how to I find the associated byte-compiled module path. (Again a


will get me a source-file name that I can try to convert to the bytecode module name, but nicer would be if there were a more reliable way since clearly Python had to read the module in the first place.

What's the most reliable way?

Answer Source

Look at the globals (it's the f_globals attribute of a frame); it has a wealth of info:

  • __name__ - the module name
  • __file__ - the module filename
  • __cached__ - the .pyc bytecode cache filename