Search code examples
pythonpython-jedi

Get a function/class code from a file knowing the line and the column of it's definition


Basically I want to use jedi to retrieve a function's or a class' code from the details of it's definition(s) (path, line, column). To be more explicit, what I really wish is to get the code from a file, that is not executed, static.


Solution

  • It seems that you can use ast and codegen to accomplish this task.

    I will post a sample of code to illustrate this:

    import ast,codegen
    
    def find_by_line(root, line):
        found = None
        if hasattr(root, "lineno"):
            if root.lineno == line:
                return root
        if hasattr(root, "body"):
            for node in root.body:
                found = find_by_line(node, line)
                if found:
                    break
        return found
    
    def get_func_code(path, line):
        with open(path) as file:
            code_tree = ast.parse(file.read())
            unit = find_by_line(code_tree, line)
            return codegen.to_source(unit)