我有这段代码:
import inspect
import ast
def func(foo):
return foo.bar - foo.baz
s = inspect.getsource(func)
xx = ast.parse(s)
class VisitCalls(ast.NodeVisitor):
def visit_Name(self, what):
if what.id == 'foo':
print ast.dump(what.ctx)
VisitCalls().visit(xx)
从函数'func'我想提取:
['foo.bar', 'foo.baz']
或类似的东西:
(('foo', 'bar'), ('foo', 'baz))
已编辑
一些背景来解释为什么我认为我需要这样做
我想将一个简单的 python 函数的代码转换为电子表格公式。
所以我需要转换:
foo.bar - foo.baz
至:
=A1-B1
示例电子表格 http://img441.imageshack.us/img441/1451/84516405.png
**再次编辑*
到目前为止我所拥有的。
下面的程序输出:
('A1', 5)
('B1', 3)
('C1', '= A1 - B1')
编码:
import ast, inspect
import codegen # by Armin Ronacher
from collections import OrderedDict
class SpreadSheetFormulaTransformer(ast.NodeTransformer):
def __init__(self, sym):
self.sym = sym
def visit_Attribute(self, node):
name = self.sym[id(eval(codegen.to_source(node)))]
return ast.Name(id=name, ctx=ast.Load())
def create(**kwargs):
class Foo(object): pass
x = Foo()
x.__dict__.update(kwargs)
return x
def register(x,y):
cell[y] = x
sym[id(x)] = y
def func(foo):
return foo.bar - foo.baz
foo = create(bar=5, baz=3)
cell = OrderedDict()
sym = {}
register(foo.bar, 'A1')
register(foo.baz, 'B1')
source = inspect.getsource(func)
tree = ast.parse(source)
guts = tree.body[0].body[0].value
SpreadSheetFormulaTransformer(sym).visit(guts)
code = '= ' + codegen.to_source(guts)
cell['C1'] = code
for x in cell.iteritems():
print x
我在这里找到了一些资源:Python internals: Working with Python ASTs I grabbed a working codegen module here。