Is it possible to get the code object of top level code within a module? For example, if you have a python file like this:
myvar = 1
print('hello from top level')
def myfunction():
print('hello from function')
and you want to access the code object for myfunction
, then you can use myfunction.__code__
. For example, myfunction.__code__.co_consts
will contain the string 'hello from function'
etc...
Is there a way to get the code object for the top level code? That is, for the code:
myvar = 1
print('hello from top level')
I would like something like __main__.__code__.co_consts
that will contain 'hello from top level'
, but I cannot find any way to get this. Does such a thing exist?
The code that is executed at the top level of a module is not directly accessible as a code object in the same way that functions' code objects are, because the top-level code is executed immediately when the module is imported or run, and it doesn't exist as a separate entity like a function does.
But when Python runs a script, it compiles it first to bytecode and stores it in a code object. The top-level code (
__main__
module), have a code object, but it is not directly exposed, so you need to useinspect
module to dig deeper:would yield