0

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.

khael
  • 2,600
  • 1
  • 15
  • 36

3 Answers3

0

I use the function find_pyfunc_above_row defined in this file https://github.com/Erotemic/utool/blob/next/utool/util_inspect.py to accomplish a similar task.

Erotemic
  • 4,806
  • 4
  • 39
  • 80
  • `find_pyfunc_above_row` gets me the function name, and for `get_func_sourcecode` I woud need a live function, I wanted a static code function retrieval, no live code whatsoever. Does `utool` provide such a functionality, or am I missing something? – khael Mar 02 '16 at 14:17
  • 1
    No, I don't think you're missing anything. I thought that function did a bit more than it did. Most of utool's inspection capability uses live code objects. You could however, ust ast's parse tree to just parse the file after the line that you know the function is on and then grab the code from visit_FunctionDef. Take a look at find_child_kwarg_funcs in the same file, which does static analysis. You can get source code from a parse tree. – Erotemic Mar 02 '16 at 14:30
0

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)
khael
  • 2,600
  • 1
  • 15
  • 36
0

This is currently not something that is supported in Jedi. You could certainly do it, but not with the public API. There are two things that Jedi's API is currently missing:

  1. Getting the class/function by position (You can get this by playing with jedi's Parser).
  2. Getting the code once you have your class. This is very easy: node.get_code()

Try to play with jedi.parser.Parser. It's quite a powerful tool, but not yet publicly documented.

Dave Halter
  • 15,556
  • 13
  • 76
  • 103