I have a python function x that returns some module
x():
return y
I would like to parse the file x is located in and learn that "x returns this thing called 'y'". I have no idea how.
I'm not trying to get the type of the return type, just what the programmer calls exactly what is being returned.
Best Answer
Use the
ast
moduleThis defines a function which takes some python source's filename and a function name
fname
(your "x
") and yields each identifier returned by functionfname
. Here, I assume that you are only interested inreturn
statements that occur at the first level of functionx
and consequently, I don't visit subexpressions. Also, I'am usingyield
because in more general cases this could work like a filter which could be composed with other ones. In more complex cases, it can be preferable to subclassast.NodeVisitor
.This is equivalent in size with the regex approach but far more reliable.