import ast
def extract_return(file, fname):
for x in ast.walk(ast.parse(open(file).read())):
if not(isinstance(x, ast.FunctionDef)):
continue
if not(x.name == fname):
continue
for b in x.body:
if isinstance(b, ast.Return):
if isinstance(b.value, ast.Name):
yield b.value.id
This defines a function which takes some python source's filename and a function name fname (your "x") and yields each identifier returned by function fname. Here, I assume that you are only interested in return statements that occur at the first level of function x and consequently, I don't visit subexpressions. Also, I'am using yield 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 subclass ast.NodeVisitor.
This is equivalent in size with the regex approach but far more reliable.
returned_object.__name__?