pythontoplevel

In Python is there a way to get the code object of top level code?


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?


Solution

  • 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 use inspect module to dig deeper:

    import inspect
    
    def get_top_level_code_object():
        frame = inspect.currentframe()
    
        # Go back to the top-level frame
        while frame.f_back:
            frame = frame.f_back
    
        # The code object is stored in f_code
        return frame.f_code
    
    if __name__ == "__main__":
        top_level_code_obj = get_top_level_code_object()
        print(top_level_code_obj.co_consts) 
    

    would yield

    (0, None, <code object get_top_level_code_object at 0x7f970ad658f0, file "/tmp/test.py", line 3>, '__main__')