2

How can one make a ast tree inspectable by inspect.getsource()

exec(compile(create_module(...), 'foo.py', 'exec'))
print(inspect.getsource(obj.instance.method))

inspect.getsource() returns just a newline terminated string.

hooblei
  • 3,210
  • 2
  • 20
  • 17
  • From what I understand, you want to take an AST and create the code that matches it. There is no simple way of doing this. There are some packages that do it. See http://stackoverflow.com/questions/768634/parse-a-py-file-read-the-ast-modify-it-then-write-back-the-modified-source-c – Ella Sharakanski Apr 22 '15 at 15:13
  • @EllaShar Not quite - I'm reading various pg schema informations and create python objects, classes, methods, etc, which works quite well. The only thing I'm stuck is the `inspect.getsource()`. – hooblei Apr 22 '15 at 15:24
  • By "create" you mean you manage to print their source code, or do you mean you just generate those objects? `getsource()` prints source code, so how is it different from what I said? – Ella Sharakanski Apr 22 '15 at 15:36
  • @EllaShar I'm constructing an ast tree by `ast.Module(body=[ast.ClassDef(... etc`. I do not generate Python source by any kind of string manipulation. In you linked SO thread is a mention of [codegen](https://pypi.python.org/pypi/codegen/1.0) that might help. – hooblei Apr 22 '15 at 15:49
  • That's what I thought you're doing. But `getsource()` generates string. That's what you wanted to do. Right? – Ella Sharakanski Apr 22 '15 at 16:10
  • Yupp - I would like to have a look on what the generated ast is in python code. – hooblei Apr 22 '15 at 16:56
  • So as I said before, some packages do that but there is no simple built in way. – Ella Sharakanski Apr 22 '15 at 17:02

0 Answers0