alexmojaki / executing

Get information about what a Python frame is currently doing, particularly the AST node being executed
MIT License
326 stars 32 forks source link

Request for help: a function that accepts (filename, qualname), finds that function and returns its source code #72

Closed jschall closed 11 months ago

jschall commented 1 year ago

I am trying to make a caching system that must check a hash of the source of a function and all of the functions that it calls.

So far, I am able to use settrace and executing to get the filename and qualname of the function. What I haven't been able to figure out is how to retrieve the source given a filename and qualname.

I figure this would be right up the alley of a developer on this project. Help would be much appreciated ;)

Better ideas for implementing such a caching system are also appreciated.

pwwang commented 1 year ago

Is asttokens able to give the source for you?

alexmojaki commented 1 year ago

If you have a code object, which you can get easily while using settrace, you can pass that directly to inspect.getsource, e.g:

import inspect

def foo():
    print(inspect.getsource(inspect.currentframe().f_code))

foo()

If for some reason you only have the filename and qualname, then it's more complicated. You could iterate through all code objects in the file by recursing through code objects in code.co_consts to find one with a matching qualname. But I don't know a way to get the original root code object from a filename, so you'd probably have to compile a new one from the file's source.

Alternatively, take a look at how executing finds the qualnames using the AST, use the idea to retrieve an AST node based on the qualname, and then get the source with asttokens.