我的目标是确定一行的方法/功能.例如,在scenario.py中有两个函数,它们只有一行代码.我的工作是我有一个大型应用程序,我将解析该应用程序中的所有python文件,并识别具有一行的函数.
#Scenario.py
line 1---> class parent:
line 2---> def father(self):
line 3---> print "dad"
line 4---> def mother(self):
line 5---> print "mom"
Sample Output:
One liner function at : line=2, line =4
Run Code Online (Sandbox Code Playgroud)
使用ast:
import ast
def iter_functions(code):
tree = ast.parse(code)
for x in tree.body:
if isinstance(x, ast.FunctionDef):
yield x
elif isinstance(x, ast.ClassDef):
for x in tree.body:
for y in x.body:
yield y
code = r'''class parent:
def father(self):
print "dad"
def mother(self):
print "mom"
def grandfather(self):
print "grand"
print "dad"
'''
# This is incorrect. See UPDATE
for f in iter_functions(code):
if len(f.body) > 0 and len({stmt.lineno for stmt in f.body}) == 1:
print(f.lineno)
Run Code Online (Sandbox Code Playgroud)
版画
2
4
Run Code Online (Sandbox Code Playgroud)
注意
如果代码中存在语法错误,则此代码将引发SyntaxError.此外,如果您尝试使用Python 2解析Python 3代码(反之亦然),它可能会引发(并非总是).SyntaxError
上述for声明应替换为以下内容:
for f in iter_functions(code):
if len({node.lineno for stmt in f.body for node in ast.walk(stmt)
if hasattr(node, 'lineno')}) == 1:
print(f.lineno)
Run Code Online (Sandbox Code Playgroud)
否则,以下功能被视为oneliner:
def func():
if True:
pass
Run Code Online (Sandbox Code Playgroud)